id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
238,400 | googleapis/dialogflow-python-client-v2 | samples/detect_intent_with_sentiment_analysis.py | detect_intent_with_sentiment_analysis | def detect_intent_with_sentiment_analysis(project_id, session_id, texts,
language_code):
"""Returns the result of detect intent with texts as inputs and analyzes the
sentiment of the query text.
Using the same `session_id` between requests allows continuation
of the conversaion."""
import dialogflow_v2beta1 as dialogflow
session_client = dialogflow.SessionsClient()
session_path = session_client.session_path(project_id, session_id)
print('Session path: {}\n'.format(session_path))
for text in texts:
text_input = dialogflow.types.TextInput(
text=text, language_code=language_code)
query_input = dialogflow.types.QueryInput(text=text_input)
# Enable sentiment analysis
sentiment_config = dialogflow.types.SentimentAnalysisRequestConfig(
analyze_query_text_sentiment=True)
# Set the query parameters with sentiment analysis
query_params = dialogflow.types.QueryParameters(
sentiment_analysis_request_config=sentiment_config)
response = session_client.detect_intent(
session=session_path, query_input=query_input,
query_params=query_params)
print('=' * 20)
print('Query text: {}'.format(response.query_result.query_text))
print('Detected intent: {} (confidence: {})\n'.format(
response.query_result.intent.display_name,
response.query_result.intent_detection_confidence))
print('Fulfillment text: {}\n'.format(
response.query_result.fulfillment_text))
# Score between -1.0 (negative sentiment) and 1.0 (positive sentiment).
print('Query Text Sentiment Score: {}\n'.format(
response.query_result.sentiment_analysis_result
.query_text_sentiment.score))
print('Query Text Sentiment Magnitude: {}\n'.format(
response.query_result.sentiment_analysis_result
.query_text_sentiment.magnitude)) | python | def detect_intent_with_sentiment_analysis(project_id, session_id, texts,
language_code):
import dialogflow_v2beta1 as dialogflow
session_client = dialogflow.SessionsClient()
session_path = session_client.session_path(project_id, session_id)
print('Session path: {}\n'.format(session_path))
for text in texts:
text_input = dialogflow.types.TextInput(
text=text, language_code=language_code)
query_input = dialogflow.types.QueryInput(text=text_input)
# Enable sentiment analysis
sentiment_config = dialogflow.types.SentimentAnalysisRequestConfig(
analyze_query_text_sentiment=True)
# Set the query parameters with sentiment analysis
query_params = dialogflow.types.QueryParameters(
sentiment_analysis_request_config=sentiment_config)
response = session_client.detect_intent(
session=session_path, query_input=query_input,
query_params=query_params)
print('=' * 20)
print('Query text: {}'.format(response.query_result.query_text))
print('Detected intent: {} (confidence: {})\n'.format(
response.query_result.intent.display_name,
response.query_result.intent_detection_confidence))
print('Fulfillment text: {}\n'.format(
response.query_result.fulfillment_text))
# Score between -1.0 (negative sentiment) and 1.0 (positive sentiment).
print('Query Text Sentiment Score: {}\n'.format(
response.query_result.sentiment_analysis_result
.query_text_sentiment.score))
print('Query Text Sentiment Magnitude: {}\n'.format(
response.query_result.sentiment_analysis_result
.query_text_sentiment.magnitude)) | [
"def",
"detect_intent_with_sentiment_analysis",
"(",
"project_id",
",",
"session_id",
",",
"texts",
",",
"language_code",
")",
":",
"import",
"dialogflow_v2beta1",
"as",
"dialogflow",
"session_client",
"=",
"dialogflow",
".",
"SessionsClient",
"(",
")",
"session_path",
... | Returns the result of detect intent with texts as inputs and analyzes the
sentiment of the query text.
Using the same `session_id` between requests allows continuation
of the conversaion. | [
"Returns",
"the",
"result",
"of",
"detect",
"intent",
"with",
"texts",
"as",
"inputs",
"and",
"analyzes",
"the",
"sentiment",
"of",
"the",
"query",
"text",
"."
] | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/detect_intent_with_sentiment_analysis.py#L31-L75 |
238,401 | googleapis/dialogflow-python-client-v2 | dialogflow_v2beta1/gapic/sessions_client.py | SessionsClient.detect_intent | def detect_intent(self,
session,
query_input,
query_params=None,
output_audio_config=None,
input_audio=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
"""
Processes a natural language query and returns structured, actionable data
as a result. This method is not idempotent, because it may cause contexts
and session entity types to be updated, which in turn might affect
results of future queries.
Example:
>>> import dialogflow_v2beta1
>>>
>>> client = dialogflow_v2beta1.SessionsClient()
>>>
>>> session = client.session_path('[PROJECT]', '[SESSION]')
>>>
>>> # TODO: Initialize ``query_input``:
>>> query_input = {}
>>>
>>> response = client.detect_intent(session, query_input)
Args:
session (str): Required. The name of the session this query is sent to. Format:
``projects/<Project ID>/agent/sessions/<Session ID>``, or
``projects/<Project ID>/agent/environments/<Environment ID>/users/<User
ID>/sessions/<Session ID>``. If ``Environment ID`` is not specified, we assume
default 'draft' environment. If ``User ID`` is not specified, we are using
\"-\". It’s up to the API caller to choose an appropriate ``Session ID`` and
``User Id``. They can be a random numbers or some type of user and session
identifiers (preferably hashed). The length of the ``Session ID`` and
``User ID`` must not exceed 36 characters.
query_input (Union[dict, ~google.cloud.dialogflow_v2beta1.types.QueryInput]): Required. The input specification. It can be set to:
1. an audio config
::
which instructs the speech recognizer how to process the speech audio,
2. a conversational query in the form of text, or
3. an event that specifies which intent to trigger.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.dialogflow_v2beta1.types.QueryInput`
query_params (Union[dict, ~google.cloud.dialogflow_v2beta1.types.QueryParameters]): Optional. The parameters of this query.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.dialogflow_v2beta1.types.QueryParameters`
output_audio_config (Union[dict, ~google.cloud.dialogflow_v2beta1.types.OutputAudioConfig]): Optional. Instructs the speech synthesizer how to generate the output
audio. If this field is not set and agent-level speech synthesizer is not
configured, no output audio is generated.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.dialogflow_v2beta1.types.OutputAudioConfig`
input_audio (bytes): Optional. The natural language speech audio to be processed. This field
should be populated iff ``query_input`` is set to an input audio config.
A single request can contain up to 1 minute of speech audio data.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.dialogflow_v2beta1.types.DetectIntentResponse` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if 'detect_intent' not in self._inner_api_calls:
self._inner_api_calls[
'detect_intent'] = google.api_core.gapic_v1.method.wrap_method(
self.transport.detect_intent,
default_retry=self._method_configs['DetectIntent'].retry,
default_timeout=self._method_configs['DetectIntent']
.timeout,
client_info=self._client_info,
)
request = session_pb2.DetectIntentRequest(
session=session,
query_input=query_input,
query_params=query_params,
output_audio_config=output_audio_config,
input_audio=input_audio,
)
return self._inner_api_calls['detect_intent'](
request, retry=retry, timeout=timeout, metadata=metadata) | python | def detect_intent(self,
session,
query_input,
query_params=None,
output_audio_config=None,
input_audio=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
# Wrap the transport method to add retry and timeout logic.
if 'detect_intent' not in self._inner_api_calls:
self._inner_api_calls[
'detect_intent'] = google.api_core.gapic_v1.method.wrap_method(
self.transport.detect_intent,
default_retry=self._method_configs['DetectIntent'].retry,
default_timeout=self._method_configs['DetectIntent']
.timeout,
client_info=self._client_info,
)
request = session_pb2.DetectIntentRequest(
session=session,
query_input=query_input,
query_params=query_params,
output_audio_config=output_audio_config,
input_audio=input_audio,
)
return self._inner_api_calls['detect_intent'](
request, retry=retry, timeout=timeout, metadata=metadata) | [
"def",
"detect_intent",
"(",
"self",
",",
"session",
",",
"query_input",
",",
"query_params",
"=",
"None",
",",
"output_audio_config",
"=",
"None",
",",
"input_audio",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",... | Processes a natural language query and returns structured, actionable data
as a result. This method is not idempotent, because it may cause contexts
and session entity types to be updated, which in turn might affect
results of future queries.
Example:
>>> import dialogflow_v2beta1
>>>
>>> client = dialogflow_v2beta1.SessionsClient()
>>>
>>> session = client.session_path('[PROJECT]', '[SESSION]')
>>>
>>> # TODO: Initialize ``query_input``:
>>> query_input = {}
>>>
>>> response = client.detect_intent(session, query_input)
Args:
session (str): Required. The name of the session this query is sent to. Format:
``projects/<Project ID>/agent/sessions/<Session ID>``, or
``projects/<Project ID>/agent/environments/<Environment ID>/users/<User
ID>/sessions/<Session ID>``. If ``Environment ID`` is not specified, we assume
default 'draft' environment. If ``User ID`` is not specified, we are using
\"-\". It’s up to the API caller to choose an appropriate ``Session ID`` and
``User Id``. They can be a random numbers or some type of user and session
identifiers (preferably hashed). The length of the ``Session ID`` and
``User ID`` must not exceed 36 characters.
query_input (Union[dict, ~google.cloud.dialogflow_v2beta1.types.QueryInput]): Required. The input specification. It can be set to:
1. an audio config
::
which instructs the speech recognizer how to process the speech audio,
2. a conversational query in the form of text, or
3. an event that specifies which intent to trigger.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.dialogflow_v2beta1.types.QueryInput`
query_params (Union[dict, ~google.cloud.dialogflow_v2beta1.types.QueryParameters]): Optional. The parameters of this query.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.dialogflow_v2beta1.types.QueryParameters`
output_audio_config (Union[dict, ~google.cloud.dialogflow_v2beta1.types.OutputAudioConfig]): Optional. Instructs the speech synthesizer how to generate the output
audio. If this field is not set and agent-level speech synthesizer is not
configured, no output audio is generated.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.dialogflow_v2beta1.types.OutputAudioConfig`
input_audio (bytes): Optional. The natural language speech audio to be processed. This field
should be populated iff ``query_input`` is set to an input audio config.
A single request can contain up to 1 minute of speech audio data.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.dialogflow_v2beta1.types.DetectIntentResponse` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Processes",
"a",
"natural",
"language",
"query",
"and",
"returns",
"structured",
"actionable",
"data",
"as",
"a",
"result",
".",
"This",
"method",
"is",
"not",
"idempotent",
"because",
"it",
"may",
"cause",
"contexts",
"and",
"session",
"entity",
"types",
"to... | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2beta1/gapic/sessions_client.py#L201-L299 |
238,402 | googleapis/dialogflow-python-client-v2 | samples/detect_intent_stream.py | detect_intent_stream | def detect_intent_stream(project_id, session_id, audio_file_path,
language_code):
"""Returns the result of detect intent with streaming audio as input.
Using the same `session_id` between requests allows continuation
of the conversaion."""
import dialogflow_v2 as dialogflow
session_client = dialogflow.SessionsClient()
# Note: hard coding audio_encoding and sample_rate_hertz for simplicity.
audio_encoding = dialogflow.enums.AudioEncoding.AUDIO_ENCODING_LINEAR_16
sample_rate_hertz = 16000
session_path = session_client.session_path(project_id, session_id)
print('Session path: {}\n'.format(session_path))
def request_generator(audio_config, audio_file_path):
query_input = dialogflow.types.QueryInput(audio_config=audio_config)
# The first request contains the configuration.
yield dialogflow.types.StreamingDetectIntentRequest(
session=session_path, query_input=query_input)
# Here we are reading small chunks of audio data from a local
# audio file. In practice these chunks should come from
# an audio input device.
with open(audio_file_path, 'rb') as audio_file:
while True:
chunk = audio_file.read(4096)
if not chunk:
break
# The later requests contains audio data.
yield dialogflow.types.StreamingDetectIntentRequest(
input_audio=chunk)
audio_config = dialogflow.types.InputAudioConfig(
audio_encoding=audio_encoding, language_code=language_code,
sample_rate_hertz=sample_rate_hertz)
requests = request_generator(audio_config, audio_file_path)
responses = session_client.streaming_detect_intent(requests)
print('=' * 20)
for response in responses:
print('Intermediate transcript: "{}".'.format(
response.recognition_result.transcript))
# Note: The result from the last response is the final transcript along
# with the detected content.
query_result = response.query_result
print('=' * 20)
print('Query text: {}'.format(query_result.query_text))
print('Detected intent: {} (confidence: {})\n'.format(
query_result.intent.display_name,
query_result.intent_detection_confidence))
print('Fulfillment text: {}\n'.format(
query_result.fulfillment_text)) | python | def detect_intent_stream(project_id, session_id, audio_file_path,
language_code):
import dialogflow_v2 as dialogflow
session_client = dialogflow.SessionsClient()
# Note: hard coding audio_encoding and sample_rate_hertz for simplicity.
audio_encoding = dialogflow.enums.AudioEncoding.AUDIO_ENCODING_LINEAR_16
sample_rate_hertz = 16000
session_path = session_client.session_path(project_id, session_id)
print('Session path: {}\n'.format(session_path))
def request_generator(audio_config, audio_file_path):
query_input = dialogflow.types.QueryInput(audio_config=audio_config)
# The first request contains the configuration.
yield dialogflow.types.StreamingDetectIntentRequest(
session=session_path, query_input=query_input)
# Here we are reading small chunks of audio data from a local
# audio file. In practice these chunks should come from
# an audio input device.
with open(audio_file_path, 'rb') as audio_file:
while True:
chunk = audio_file.read(4096)
if not chunk:
break
# The later requests contains audio data.
yield dialogflow.types.StreamingDetectIntentRequest(
input_audio=chunk)
audio_config = dialogflow.types.InputAudioConfig(
audio_encoding=audio_encoding, language_code=language_code,
sample_rate_hertz=sample_rate_hertz)
requests = request_generator(audio_config, audio_file_path)
responses = session_client.streaming_detect_intent(requests)
print('=' * 20)
for response in responses:
print('Intermediate transcript: "{}".'.format(
response.recognition_result.transcript))
# Note: The result from the last response is the final transcript along
# with the detected content.
query_result = response.query_result
print('=' * 20)
print('Query text: {}'.format(query_result.query_text))
print('Detected intent: {} (confidence: {})\n'.format(
query_result.intent.display_name,
query_result.intent_detection_confidence))
print('Fulfillment text: {}\n'.format(
query_result.fulfillment_text)) | [
"def",
"detect_intent_stream",
"(",
"project_id",
",",
"session_id",
",",
"audio_file_path",
",",
"language_code",
")",
":",
"import",
"dialogflow_v2",
"as",
"dialogflow",
"session_client",
"=",
"dialogflow",
".",
"SessionsClient",
"(",
")",
"# Note: hard coding audio_e... | Returns the result of detect intent with streaming audio as input.
Using the same `session_id` between requests allows continuation
of the conversaion. | [
"Returns",
"the",
"result",
"of",
"detect",
"intent",
"with",
"streaming",
"audio",
"as",
"input",
"."
] | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/detect_intent_stream.py#L33-L90 |
238,403 | googleapis/dialogflow-python-client-v2 | samples/intent_management.py | create_intent | def create_intent(project_id, display_name, training_phrases_parts,
message_texts):
"""Create an intent of the given intent type."""
import dialogflow_v2 as dialogflow
intents_client = dialogflow.IntentsClient()
parent = intents_client.project_agent_path(project_id)
training_phrases = []
for training_phrases_part in training_phrases_parts:
part = dialogflow.types.Intent.TrainingPhrase.Part(
text=training_phrases_part)
# Here we create a new training phrase for each provided part.
training_phrase = dialogflow.types.Intent.TrainingPhrase(parts=[part])
training_phrases.append(training_phrase)
text = dialogflow.types.Intent.Message.Text(text=message_texts)
message = dialogflow.types.Intent.Message(text=text)
intent = dialogflow.types.Intent(
display_name=display_name,
training_phrases=training_phrases,
messages=[message])
response = intents_client.create_intent(parent, intent)
print('Intent created: {}'.format(response)) | python | def create_intent(project_id, display_name, training_phrases_parts,
message_texts):
import dialogflow_v2 as dialogflow
intents_client = dialogflow.IntentsClient()
parent = intents_client.project_agent_path(project_id)
training_phrases = []
for training_phrases_part in training_phrases_parts:
part = dialogflow.types.Intent.TrainingPhrase.Part(
text=training_phrases_part)
# Here we create a new training phrase for each provided part.
training_phrase = dialogflow.types.Intent.TrainingPhrase(parts=[part])
training_phrases.append(training_phrase)
text = dialogflow.types.Intent.Message.Text(text=message_texts)
message = dialogflow.types.Intent.Message(text=text)
intent = dialogflow.types.Intent(
display_name=display_name,
training_phrases=training_phrases,
messages=[message])
response = intents_client.create_intent(parent, intent)
print('Intent created: {}'.format(response)) | [
"def",
"create_intent",
"(",
"project_id",
",",
"display_name",
",",
"training_phrases_parts",
",",
"message_texts",
")",
":",
"import",
"dialogflow_v2",
"as",
"dialogflow",
"intents_client",
"=",
"dialogflow",
".",
"IntentsClient",
"(",
")",
"parent",
"=",
"intents... | Create an intent of the given intent type. | [
"Create",
"an",
"intent",
"of",
"the",
"given",
"intent",
"type",
"."
] | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/intent_management.py#L63-L88 |
238,404 | googleapis/dialogflow-python-client-v2 | samples/intent_management.py | delete_intent | def delete_intent(project_id, intent_id):
"""Delete intent with the given intent type and intent value."""
import dialogflow_v2 as dialogflow
intents_client = dialogflow.IntentsClient()
intent_path = intents_client.intent_path(project_id, intent_id)
intents_client.delete_intent(intent_path) | python | def delete_intent(project_id, intent_id):
import dialogflow_v2 as dialogflow
intents_client = dialogflow.IntentsClient()
intent_path = intents_client.intent_path(project_id, intent_id)
intents_client.delete_intent(intent_path) | [
"def",
"delete_intent",
"(",
"project_id",
",",
"intent_id",
")",
":",
"import",
"dialogflow_v2",
"as",
"dialogflow",
"intents_client",
"=",
"dialogflow",
".",
"IntentsClient",
"(",
")",
"intent_path",
"=",
"intents_client",
".",
"intent_path",
"(",
"project_id",
... | Delete intent with the given intent type and intent value. | [
"Delete",
"intent",
"with",
"the",
"given",
"intent",
"type",
"and",
"intent",
"value",
"."
] | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/intent_management.py#L93-L100 |
238,405 | googleapis/dialogflow-python-client-v2 | dialogflow_v2/gapic/agents_client.py | AgentsClient.get_agent | def get_agent(self,
parent,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
"""
Retrieves the specified agent.
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.AgentsClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> response = client.get_agent(parent)
Args:
parent (str): Required. The project that the agent to fetch is associated with.
Format: ``projects/<Project ID>``.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.dialogflow_v2.types.Agent` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if 'get_agent' not in self._inner_api_calls:
self._inner_api_calls[
'get_agent'] = google.api_core.gapic_v1.method.wrap_method(
self.transport.get_agent,
default_retry=self._method_configs['GetAgent'].retry,
default_timeout=self._method_configs['GetAgent'].timeout,
client_info=self._client_info,
)
request = agent_pb2.GetAgentRequest(parent=parent, )
return self._inner_api_calls['get_agent'](
request, retry=retry, timeout=timeout, metadata=metadata) | python | def get_agent(self,
parent,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
# Wrap the transport method to add retry and timeout logic.
if 'get_agent' not in self._inner_api_calls:
self._inner_api_calls[
'get_agent'] = google.api_core.gapic_v1.method.wrap_method(
self.transport.get_agent,
default_retry=self._method_configs['GetAgent'].retry,
default_timeout=self._method_configs['GetAgent'].timeout,
client_info=self._client_info,
)
request = agent_pb2.GetAgentRequest(parent=parent, )
return self._inner_api_calls['get_agent'](
request, retry=retry, timeout=timeout, metadata=metadata) | [
"def",
"get_agent",
"(",
"self",
",",
"parent",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",... | Retrieves the specified agent.
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.AgentsClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> response = client.get_agent(parent)
Args:
parent (str): Required. The project that the agent to fetch is associated with.
Format: ``projects/<Project ID>``.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.dialogflow_v2.types.Agent` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Retrieves",
"the",
"specified",
"agent",
"."
] | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/agents_client.py#L197-L248 |
238,406 | googleapis/dialogflow-python-client-v2 | dialogflow_v2/gapic/agents_client.py | AgentsClient.train_agent | def train_agent(self,
parent,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
"""
Trains the specified agent.
Operation <response: ``google.protobuf.Empty``,
metadata: [google.protobuf.Struct][google.protobuf.Struct]>
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.AgentsClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> response = client.train_agent(parent)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
parent (str): Required. The project that the agent to train is associated with.
Format: ``projects/<Project ID>``.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if 'train_agent' not in self._inner_api_calls:
self._inner_api_calls[
'train_agent'] = google.api_core.gapic_v1.method.wrap_method(
self.transport.train_agent,
default_retry=self._method_configs['TrainAgent'].retry,
default_timeout=self._method_configs['TrainAgent'].timeout,
client_info=self._client_info,
)
request = agent_pb2.TrainAgentRequest(parent=parent, )
operation = self._inner_api_calls['train_agent'](
request, retry=retry, timeout=timeout, metadata=metadata)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
empty_pb2.Empty,
metadata_type=struct_pb2.Struct,
) | python | def train_agent(self,
parent,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
# Wrap the transport method to add retry and timeout logic.
if 'train_agent' not in self._inner_api_calls:
self._inner_api_calls[
'train_agent'] = google.api_core.gapic_v1.method.wrap_method(
self.transport.train_agent,
default_retry=self._method_configs['TrainAgent'].retry,
default_timeout=self._method_configs['TrainAgent'].timeout,
client_info=self._client_info,
)
request = agent_pb2.TrainAgentRequest(parent=parent, )
operation = self._inner_api_calls['train_agent'](
request, retry=retry, timeout=timeout, metadata=metadata)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
empty_pb2.Empty,
metadata_type=struct_pb2.Struct,
) | [
"def",
"train_agent",
"(",
"self",
",",
"parent",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata... | Trains the specified agent.
Operation <response: ``google.protobuf.Empty``,
metadata: [google.protobuf.Struct][google.protobuf.Struct]>
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.AgentsClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> response = client.train_agent(parent)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
parent (str): Required. The project that the agent to train is associated with.
Format: ``projects/<Project ID>``.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Trains",
"the",
"specified",
"agent",
"."
] | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/agents_client.py#L345-L414 |
238,407 | googleapis/dialogflow-python-client-v2 | dialogflow_v2/gapic/agents_client.py | AgentsClient.export_agent | def export_agent(self,
parent,
agent_uri=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
"""
Exports the specified agent to a ZIP file.
Operation <response: ``ExportAgentResponse``,
metadata: [google.protobuf.Struct][google.protobuf.Struct]>
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.AgentsClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> response = client.export_agent(parent)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
parent (str): Required. The project that the agent to export is associated with.
Format: ``projects/<Project ID>``.
agent_uri (str): Optional. The Google Cloud Storage URI to export the agent to.
Note: The URI must start with
\"gs://\". If left unspecified, the serialized agent is returned inline.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if 'export_agent' not in self._inner_api_calls:
self._inner_api_calls[
'export_agent'] = google.api_core.gapic_v1.method.wrap_method(
self.transport.export_agent,
default_retry=self._method_configs['ExportAgent'].retry,
default_timeout=self._method_configs['ExportAgent']
.timeout,
client_info=self._client_info,
)
request = agent_pb2.ExportAgentRequest(
parent=parent,
agent_uri=agent_uri,
)
operation = self._inner_api_calls['export_agent'](
request, retry=retry, timeout=timeout, metadata=metadata)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
agent_pb2.ExportAgentResponse,
metadata_type=struct_pb2.Struct,
) | python | def export_agent(self,
parent,
agent_uri=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
# Wrap the transport method to add retry and timeout logic.
if 'export_agent' not in self._inner_api_calls:
self._inner_api_calls[
'export_agent'] = google.api_core.gapic_v1.method.wrap_method(
self.transport.export_agent,
default_retry=self._method_configs['ExportAgent'].retry,
default_timeout=self._method_configs['ExportAgent']
.timeout,
client_info=self._client_info,
)
request = agent_pb2.ExportAgentRequest(
parent=parent,
agent_uri=agent_uri,
)
operation = self._inner_api_calls['export_agent'](
request, retry=retry, timeout=timeout, metadata=metadata)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
agent_pb2.ExportAgentResponse,
metadata_type=struct_pb2.Struct,
) | [
"def",
"export_agent",
"(",
"self",
",",
"parent",
",",
"agent_uri",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method"... | Exports the specified agent to a ZIP file.
Operation <response: ``ExportAgentResponse``,
metadata: [google.protobuf.Struct][google.protobuf.Struct]>
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.AgentsClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> response = client.export_agent(parent)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
parent (str): Required. The project that the agent to export is associated with.
Format: ``projects/<Project ID>``.
agent_uri (str): Optional. The Google Cloud Storage URI to export the agent to.
Note: The URI must start with
\"gs://\". If left unspecified, the serialized agent is returned inline.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Exports",
"the",
"specified",
"agent",
"to",
"a",
"ZIP",
"file",
"."
] | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/agents_client.py#L416-L493 |
238,408 | googleapis/dialogflow-python-client-v2 | dialogflow_v2/gapic/agents_client.py | AgentsClient.import_agent | def import_agent(self,
parent,
agent_uri=None,
agent_content=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
"""
Imports the specified agent from a ZIP file.
Uploads new intents and entity types without deleting the existing ones.
Intents and entity types with the same name are replaced with the new
versions from ImportAgentRequest.
Operation <response: ``google.protobuf.Empty``,
metadata: [google.protobuf.Struct][google.protobuf.Struct]>
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.AgentsClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> response = client.import_agent(parent)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
parent (str): Required. The project that the agent to import is associated with.
Format: ``projects/<Project ID>``.
agent_uri (str): The URI to a Google Cloud Storage file containing the agent to import.
Note: The URI must start with \"gs://\".
agent_content (bytes): The agent to import.
Example for how to import an agent via the command line:
curl \
'https://dialogflow.googleapis.com/v2/projects/<project_name>/agent:import\
-X POST \
-H 'Authorization: Bearer '$(gcloud auth print-access-token) \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
--compressed \
--data-binary \"{
::
'agentContent': '$(cat <agent zip file> | base64 -w 0)'
}\"
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if 'import_agent' not in self._inner_api_calls:
self._inner_api_calls[
'import_agent'] = google.api_core.gapic_v1.method.wrap_method(
self.transport.import_agent,
default_retry=self._method_configs['ImportAgent'].retry,
default_timeout=self._method_configs['ImportAgent']
.timeout,
client_info=self._client_info,
)
# Sanity check: We have some fields which are mutually exclusive;
# raise ValueError if more than one is sent.
google.api_core.protobuf_helpers.check_oneof(
agent_uri=agent_uri,
agent_content=agent_content,
)
request = agent_pb2.ImportAgentRequest(
parent=parent,
agent_uri=agent_uri,
agent_content=agent_content,
)
operation = self._inner_api_calls['import_agent'](
request, retry=retry, timeout=timeout, metadata=metadata)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
empty_pb2.Empty,
metadata_type=struct_pb2.Struct,
) | python | def import_agent(self,
parent,
agent_uri=None,
agent_content=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
# Wrap the transport method to add retry and timeout logic.
if 'import_agent' not in self._inner_api_calls:
self._inner_api_calls[
'import_agent'] = google.api_core.gapic_v1.method.wrap_method(
self.transport.import_agent,
default_retry=self._method_configs['ImportAgent'].retry,
default_timeout=self._method_configs['ImportAgent']
.timeout,
client_info=self._client_info,
)
# Sanity check: We have some fields which are mutually exclusive;
# raise ValueError if more than one is sent.
google.api_core.protobuf_helpers.check_oneof(
agent_uri=agent_uri,
agent_content=agent_content,
)
request = agent_pb2.ImportAgentRequest(
parent=parent,
agent_uri=agent_uri,
agent_content=agent_content,
)
operation = self._inner_api_calls['import_agent'](
request, retry=retry, timeout=timeout, metadata=metadata)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
empty_pb2.Empty,
metadata_type=struct_pb2.Struct,
) | [
"def",
"import_agent",
"(",
"self",
",",
"parent",
",",
"agent_uri",
"=",
"None",
",",
"agent_content",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_co... | Imports the specified agent from a ZIP file.
Uploads new intents and entity types without deleting the existing ones.
Intents and entity types with the same name are replaced with the new
versions from ImportAgentRequest.
Operation <response: ``google.protobuf.Empty``,
metadata: [google.protobuf.Struct][google.protobuf.Struct]>
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.AgentsClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> response = client.import_agent(parent)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
parent (str): Required. The project that the agent to import is associated with.
Format: ``projects/<Project ID>``.
agent_uri (str): The URI to a Google Cloud Storage file containing the agent to import.
Note: The URI must start with \"gs://\".
agent_content (bytes): The agent to import.
Example for how to import an agent via the command line:
curl \
'https://dialogflow.googleapis.com/v2/projects/<project_name>/agent:import\
-X POST \
-H 'Authorization: Bearer '$(gcloud auth print-access-token) \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
--compressed \
--data-binary \"{
::
'agentContent': '$(cat <agent zip file> | base64 -w 0)'
}\"
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Imports",
"the",
"specified",
"agent",
"from",
"a",
"ZIP",
"file",
"."
] | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/agents_client.py#L495-L600 |
238,409 | googleapis/dialogflow-python-client-v2 | samples/document_management.py | list_documents | def list_documents(project_id, knowledge_base_id):
"""Lists the Documents belonging to a Knowledge base.
Args:
project_id: The GCP project linked with the agent.
knowledge_base_id: Id of the Knowledge base."""
import dialogflow_v2beta1 as dialogflow
client = dialogflow.DocumentsClient()
knowledge_base_path = client.knowledge_base_path(project_id,
knowledge_base_id)
print('Documents for Knowledge Id: {}'.format(knowledge_base_id))
for document in client.list_documents(knowledge_base_path):
print(' - Display Name: {}'.format(document.display_name))
print(' - Knowledge ID: {}'.format(document.name))
print(' - MIME Type: {}'.format(document.mime_type))
print(' - Knowledge Types:')
for knowledge_type in document.knowledge_types:
print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type]))
print(' - Source: {}\n'.format(document.content_uri)) | python | def list_documents(project_id, knowledge_base_id):
import dialogflow_v2beta1 as dialogflow
client = dialogflow.DocumentsClient()
knowledge_base_path = client.knowledge_base_path(project_id,
knowledge_base_id)
print('Documents for Knowledge Id: {}'.format(knowledge_base_id))
for document in client.list_documents(knowledge_base_path):
print(' - Display Name: {}'.format(document.display_name))
print(' - Knowledge ID: {}'.format(document.name))
print(' - MIME Type: {}'.format(document.mime_type))
print(' - Knowledge Types:')
for knowledge_type in document.knowledge_types:
print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type]))
print(' - Source: {}\n'.format(document.content_uri)) | [
"def",
"list_documents",
"(",
"project_id",
",",
"knowledge_base_id",
")",
":",
"import",
"dialogflow_v2beta1",
"as",
"dialogflow",
"client",
"=",
"dialogflow",
".",
"DocumentsClient",
"(",
")",
"knowledge_base_path",
"=",
"client",
".",
"knowledge_base_path",
"(",
... | Lists the Documents belonging to a Knowledge base.
Args:
project_id: The GCP project linked with the agent.
knowledge_base_id: Id of the Knowledge base. | [
"Lists",
"the",
"Documents",
"belonging",
"to",
"a",
"Knowledge",
"base",
"."
] | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/document_management.py#L43-L62 |
238,410 | googleapis/dialogflow-python-client-v2 | samples/document_management.py | create_document | def create_document(project_id, knowledge_base_id, display_name, mime_type,
knowledge_type, content_uri):
"""Creates a Document.
Args:
project_id: The GCP project linked with the agent.
knowledge_base_id: Id of the Knowledge base.
display_name: The display name of the Document.
mime_type: The mime_type of the Document. e.g. text/csv, text/html,
text/plain, text/pdf etc.
knowledge_type: The Knowledge type of the Document. e.g. FAQ,
EXTRACTIVE_QA.
content_uri: Uri of the document, e.g. gs://path/mydoc.csv,
http://mypage.com/faq.html."""
import dialogflow_v2beta1 as dialogflow
client = dialogflow.DocumentsClient()
knowledge_base_path = client.knowledge_base_path(project_id,
knowledge_base_id)
document = dialogflow.types.Document(
display_name=display_name, mime_type=mime_type,
content_uri=content_uri)
document.knowledge_types.append(
dialogflow.types.Document.KnowledgeType.Value(knowledge_type))
response = client.create_document(knowledge_base_path, document)
print('Waiting for results...')
document = response.result(timeout=90)
print('Created Document:')
print(' - Display Name: {}'.format(document.display_name))
print(' - Knowledge ID: {}'.format(document.name))
print(' - MIME Type: {}'.format(document.mime_type))
print(' - Knowledge Types:')
for knowledge_type in document.knowledge_types:
print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type]))
print(' - Source: {}\n'.format(document.content_uri)) | python | def create_document(project_id, knowledge_base_id, display_name, mime_type,
knowledge_type, content_uri):
import dialogflow_v2beta1 as dialogflow
client = dialogflow.DocumentsClient()
knowledge_base_path = client.knowledge_base_path(project_id,
knowledge_base_id)
document = dialogflow.types.Document(
display_name=display_name, mime_type=mime_type,
content_uri=content_uri)
document.knowledge_types.append(
dialogflow.types.Document.KnowledgeType.Value(knowledge_type))
response = client.create_document(knowledge_base_path, document)
print('Waiting for results...')
document = response.result(timeout=90)
print('Created Document:')
print(' - Display Name: {}'.format(document.display_name))
print(' - Knowledge ID: {}'.format(document.name))
print(' - MIME Type: {}'.format(document.mime_type))
print(' - Knowledge Types:')
for knowledge_type in document.knowledge_types:
print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type]))
print(' - Source: {}\n'.format(document.content_uri)) | [
"def",
"create_document",
"(",
"project_id",
",",
"knowledge_base_id",
",",
"display_name",
",",
"mime_type",
",",
"knowledge_type",
",",
"content_uri",
")",
":",
"import",
"dialogflow_v2beta1",
"as",
"dialogflow",
"client",
"=",
"dialogflow",
".",
"DocumentsClient",
... | Creates a Document.
Args:
project_id: The GCP project linked with the agent.
knowledge_base_id: Id of the Knowledge base.
display_name: The display name of the Document.
mime_type: The mime_type of the Document. e.g. text/csv, text/html,
text/plain, text/pdf etc.
knowledge_type: The Knowledge type of the Document. e.g. FAQ,
EXTRACTIVE_QA.
content_uri: Uri of the document, e.g. gs://path/mydoc.csv,
http://mypage.com/faq.html. | [
"Creates",
"a",
"Document",
"."
] | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/document_management.py#L67-L103 |
238,411 | googleapis/dialogflow-python-client-v2 | samples/document_management.py | get_document | def get_document(project_id, knowledge_base_id, document_id):
"""Gets a Document.
Args:
project_id: The GCP project linked with the agent.
knowledge_base_id: Id of the Knowledge base.
document_id: Id of the Document."""
import dialogflow_v2beta1 as dialogflow
client = dialogflow.DocumentsClient()
document_path = client.document_path(project_id, knowledge_base_id,
document_id)
response = client.get_document(document_path)
print('Got Document:')
print(' - Display Name: {}'.format(response.display_name))
print(' - Knowledge ID: {}'.format(response.name))
print(' - MIME Type: {}'.format(response.mime_type))
print(' - Knowledge Types:')
for knowledge_type in response.knowledge_types:
print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type]))
print(' - Source: {}\n'.format(response.content_uri)) | python | def get_document(project_id, knowledge_base_id, document_id):
import dialogflow_v2beta1 as dialogflow
client = dialogflow.DocumentsClient()
document_path = client.document_path(project_id, knowledge_base_id,
document_id)
response = client.get_document(document_path)
print('Got Document:')
print(' - Display Name: {}'.format(response.display_name))
print(' - Knowledge ID: {}'.format(response.name))
print(' - MIME Type: {}'.format(response.mime_type))
print(' - Knowledge Types:')
for knowledge_type in response.knowledge_types:
print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type]))
print(' - Source: {}\n'.format(response.content_uri)) | [
"def",
"get_document",
"(",
"project_id",
",",
"knowledge_base_id",
",",
"document_id",
")",
":",
"import",
"dialogflow_v2beta1",
"as",
"dialogflow",
"client",
"=",
"dialogflow",
".",
"DocumentsClient",
"(",
")",
"document_path",
"=",
"client",
".",
"document_path",... | Gets a Document.
Args:
project_id: The GCP project linked with the agent.
knowledge_base_id: Id of the Knowledge base.
document_id: Id of the Document. | [
"Gets",
"a",
"Document",
"."
] | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/document_management.py#L108-L128 |
238,412 | googleapis/dialogflow-python-client-v2 | samples/document_management.py | delete_document | def delete_document(project_id, knowledge_base_id, document_id):
"""Deletes a Document.
Args:
project_id: The GCP project linked with the agent.
knowledge_base_id: Id of the Knowledge base.
document_id: Id of the Document."""
import dialogflow_v2beta1 as dialogflow
client = dialogflow.DocumentsClient()
document_path = client.document_path(project_id, knowledge_base_id,
document_id)
response = client.delete_document(document_path)
print('operation running:\n {}'.format(response.operation))
print('Waiting for results...')
print('Done.\n {}'.format(response.result())) | python | def delete_document(project_id, knowledge_base_id, document_id):
import dialogflow_v2beta1 as dialogflow
client = dialogflow.DocumentsClient()
document_path = client.document_path(project_id, knowledge_base_id,
document_id)
response = client.delete_document(document_path)
print('operation running:\n {}'.format(response.operation))
print('Waiting for results...')
print('Done.\n {}'.format(response.result())) | [
"def",
"delete_document",
"(",
"project_id",
",",
"knowledge_base_id",
",",
"document_id",
")",
":",
"import",
"dialogflow_v2beta1",
"as",
"dialogflow",
"client",
"=",
"dialogflow",
".",
"DocumentsClient",
"(",
")",
"document_path",
"=",
"client",
".",
"document_pat... | Deletes a Document.
Args:
project_id: The GCP project linked with the agent.
knowledge_base_id: Id of the Knowledge base.
document_id: Id of the Document. | [
"Deletes",
"a",
"Document",
"."
] | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/document_management.py#L133-L148 |
238,413 | googleapis/dialogflow-python-client-v2 | samples/entity_management.py | create_entity | def create_entity(project_id, entity_type_id, entity_value, synonyms):
"""Create an entity of the given entity type."""
import dialogflow_v2 as dialogflow
entity_types_client = dialogflow.EntityTypesClient()
# Note: synonyms must be exactly [entity_value] if the
# entity_type's kind is KIND_LIST
synonyms = synonyms or [entity_value]
entity_type_path = entity_types_client.entity_type_path(
project_id, entity_type_id)
entity = dialogflow.types.EntityType.Entity()
entity.value = entity_value
entity.synonyms.extend(synonyms)
response = entity_types_client.batch_create_entities(
entity_type_path, [entity])
print('Entity created: {}'.format(response)) | python | def create_entity(project_id, entity_type_id, entity_value, synonyms):
import dialogflow_v2 as dialogflow
entity_types_client = dialogflow.EntityTypesClient()
# Note: synonyms must be exactly [entity_value] if the
# entity_type's kind is KIND_LIST
synonyms = synonyms or [entity_value]
entity_type_path = entity_types_client.entity_type_path(
project_id, entity_type_id)
entity = dialogflow.types.EntityType.Entity()
entity.value = entity_value
entity.synonyms.extend(synonyms)
response = entity_types_client.batch_create_entities(
entity_type_path, [entity])
print('Entity created: {}'.format(response)) | [
"def",
"create_entity",
"(",
"project_id",
",",
"entity_type_id",
",",
"entity_value",
",",
"synonyms",
")",
":",
"import",
"dialogflow_v2",
"as",
"dialogflow",
"entity_types_client",
"=",
"dialogflow",
".",
"EntityTypesClient",
"(",
")",
"# Note: synonyms must be exact... | Create an entity of the given entity type. | [
"Create",
"an",
"entity",
"of",
"the",
"given",
"entity",
"type",
"."
] | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/entity_management.py#L49-L68 |
238,414 | googleapis/dialogflow-python-client-v2 | samples/entity_management.py | delete_entity | def delete_entity(project_id, entity_type_id, entity_value):
"""Delete entity with the given entity type and entity value."""
import dialogflow_v2 as dialogflow
entity_types_client = dialogflow.EntityTypesClient()
entity_type_path = entity_types_client.entity_type_path(
project_id, entity_type_id)
entity_types_client.batch_delete_entities(
entity_type_path, [entity_value]) | python | def delete_entity(project_id, entity_type_id, entity_value):
import dialogflow_v2 as dialogflow
entity_types_client = dialogflow.EntityTypesClient()
entity_type_path = entity_types_client.entity_type_path(
project_id, entity_type_id)
entity_types_client.batch_delete_entities(
entity_type_path, [entity_value]) | [
"def",
"delete_entity",
"(",
"project_id",
",",
"entity_type_id",
",",
"entity_value",
")",
":",
"import",
"dialogflow_v2",
"as",
"dialogflow",
"entity_types_client",
"=",
"dialogflow",
".",
"EntityTypesClient",
"(",
")",
"entity_type_path",
"=",
"entity_types_client",
... | Delete entity with the given entity type and entity value. | [
"Delete",
"entity",
"with",
"the",
"given",
"entity",
"type",
"and",
"entity",
"value",
"."
] | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/entity_management.py#L73-L82 |
238,415 | lucasb-eyer/pydensecrf | pydensecrf/utils.py | softmax_to_unary | def softmax_to_unary(sm, GT_PROB=1):
"""Deprecated, use `unary_from_softmax` instead."""
warning("pydensecrf.softmax_to_unary is deprecated, use unary_from_softmax instead.")
scale = None if GT_PROB == 1 else GT_PROB
return unary_from_softmax(sm, scale, clip=None) | python | def softmax_to_unary(sm, GT_PROB=1):
warning("pydensecrf.softmax_to_unary is deprecated, use unary_from_softmax instead.")
scale = None if GT_PROB == 1 else GT_PROB
return unary_from_softmax(sm, scale, clip=None) | [
"def",
"softmax_to_unary",
"(",
"sm",
",",
"GT_PROB",
"=",
"1",
")",
":",
"warning",
"(",
"\"pydensecrf.softmax_to_unary is deprecated, use unary_from_softmax instead.\"",
")",
"scale",
"=",
"None",
"if",
"GT_PROB",
"==",
"1",
"else",
"GT_PROB",
"return",
"unary_from_... | Deprecated, use `unary_from_softmax` instead. | [
"Deprecated",
"use",
"unary_from_softmax",
"instead",
"."
] | 4d5343c398d75d7ebae34f51a47769084ba3a613 | https://github.com/lucasb-eyer/pydensecrf/blob/4d5343c398d75d7ebae34f51a47769084ba3a613/pydensecrf/utils.py#L82-L86 |
238,416 | lucasb-eyer/pydensecrf | pydensecrf/utils.py | create_pairwise_gaussian | def create_pairwise_gaussian(sdims, shape):
"""
Util function that create pairwise gaussian potentials. This works for all
image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseGaussian`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.addPairwiseGaussian`.
shape: list or tuple
The shape the CRF has.
"""
# create mesh
hcord_range = [range(s) for s in shape]
mesh = np.array(np.meshgrid(*hcord_range, indexing='ij'), dtype=np.float32)
# scale mesh accordingly
for i, s in enumerate(sdims):
mesh[i] /= s
return mesh.reshape([len(sdims), -1]) | python | def create_pairwise_gaussian(sdims, shape):
# create mesh
hcord_range = [range(s) for s in shape]
mesh = np.array(np.meshgrid(*hcord_range, indexing='ij'), dtype=np.float32)
# scale mesh accordingly
for i, s in enumerate(sdims):
mesh[i] /= s
return mesh.reshape([len(sdims), -1]) | [
"def",
"create_pairwise_gaussian",
"(",
"sdims",
",",
"shape",
")",
":",
"# create mesh",
"hcord_range",
"=",
"[",
"range",
"(",
"s",
")",
"for",
"s",
"in",
"shape",
"]",
"mesh",
"=",
"np",
".",
"array",
"(",
"np",
".",
"meshgrid",
"(",
"*",
"hcord_ran... | Util function that create pairwise gaussian potentials. This works for all
image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseGaussian`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.addPairwiseGaussian`.
shape: list or tuple
The shape the CRF has. | [
"Util",
"function",
"that",
"create",
"pairwise",
"gaussian",
"potentials",
".",
"This",
"works",
"for",
"all",
"image",
"dimensions",
".",
"For",
"the",
"2D",
"case",
"does",
"the",
"same",
"as",
"DenseCRF2D",
".",
"addPairwiseGaussian",
"."
] | 4d5343c398d75d7ebae34f51a47769084ba3a613 | https://github.com/lucasb-eyer/pydensecrf/blob/4d5343c398d75d7ebae34f51a47769084ba3a613/pydensecrf/utils.py#L89-L111 |
238,417 | lucasb-eyer/pydensecrf | pydensecrf/utils.py | create_pairwise_bilateral | def create_pairwise_bilateral(sdims, schan, img, chdim=-1):
"""
Util function that create pairwise bilateral potentials. This works for
all image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseBilateral`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.addPairwiseBilateral`.
schan: list or tuple
The scaling factors per channel in the image. This is referred to
`srgb` in `DenseCRF2D.addPairwiseBilateral`.
img: numpy.array
The input image.
chdim: int, optional
This specifies where the channel dimension is in the image. For
example `chdim=2` for a RGB image of size (240, 300, 3). If the
image has no channel dimension (e.g. it has only one channel) use
`chdim=-1`.
"""
# Put channel dim in right position
if chdim == -1:
# We don't have a channel, add a new axis
im_feat = img[np.newaxis].astype(np.float32)
else:
# Put the channel dim as axis 0, all others stay relatively the same
im_feat = np.rollaxis(img, chdim).astype(np.float32)
# scale image features per channel
# Allow for a single number in `schan` to broadcast across all channels:
if isinstance(schan, Number):
im_feat /= schan
else:
for i, s in enumerate(schan):
im_feat[i] /= s
# create a mesh
cord_range = [range(s) for s in im_feat.shape[1:]]
mesh = np.array(np.meshgrid(*cord_range, indexing='ij'), dtype=np.float32)
# scale mesh accordingly
for i, s in enumerate(sdims):
mesh[i] /= s
feats = np.concatenate([mesh, im_feat])
return feats.reshape([feats.shape[0], -1]) | python | def create_pairwise_bilateral(sdims, schan, img, chdim=-1):
# Put channel dim in right position
if chdim == -1:
# We don't have a channel, add a new axis
im_feat = img[np.newaxis].astype(np.float32)
else:
# Put the channel dim as axis 0, all others stay relatively the same
im_feat = np.rollaxis(img, chdim).astype(np.float32)
# scale image features per channel
# Allow for a single number in `schan` to broadcast across all channels:
if isinstance(schan, Number):
im_feat /= schan
else:
for i, s in enumerate(schan):
im_feat[i] /= s
# create a mesh
cord_range = [range(s) for s in im_feat.shape[1:]]
mesh = np.array(np.meshgrid(*cord_range, indexing='ij'), dtype=np.float32)
# scale mesh accordingly
for i, s in enumerate(sdims):
mesh[i] /= s
feats = np.concatenate([mesh, im_feat])
return feats.reshape([feats.shape[0], -1]) | [
"def",
"create_pairwise_bilateral",
"(",
"sdims",
",",
"schan",
",",
"img",
",",
"chdim",
"=",
"-",
"1",
")",
":",
"# Put channel dim in right position",
"if",
"chdim",
"==",
"-",
"1",
":",
"# We don't have a channel, add a new axis",
"im_feat",
"=",
"img",
"[",
... | Util function that create pairwise bilateral potentials. This works for
all image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseBilateral`.
Parameters
----------
sdims: list or tuple
The scaling factors per dimension. This is referred to `sxy` in
`DenseCRF2D.addPairwiseBilateral`.
schan: list or tuple
The scaling factors per channel in the image. This is referred to
`srgb` in `DenseCRF2D.addPairwiseBilateral`.
img: numpy.array
The input image.
chdim: int, optional
This specifies where the channel dimension is in the image. For
example `chdim=2` for a RGB image of size (240, 300, 3). If the
image has no channel dimension (e.g. it has only one channel) use
`chdim=-1`. | [
"Util",
"function",
"that",
"create",
"pairwise",
"bilateral",
"potentials",
".",
"This",
"works",
"for",
"all",
"image",
"dimensions",
".",
"For",
"the",
"2D",
"case",
"does",
"the",
"same",
"as",
"DenseCRF2D",
".",
"addPairwiseBilateral",
"."
] | 4d5343c398d75d7ebae34f51a47769084ba3a613 | https://github.com/lucasb-eyer/pydensecrf/blob/4d5343c398d75d7ebae34f51a47769084ba3a613/pydensecrf/utils.py#L114-L162 |
238,418 | deanmalmgren/textract | textract/parsers/odt_parser.py | Parser.to_string | def to_string(self):
""" Converts the document to a string. """
buff = u""
for child in self.content.iter():
if child.tag in [self.qn('text:p'), self.qn('text:h')]:
buff += self.text_to_string(child) + "\n"
# remove last newline char
if buff:
buff = buff[:-1]
return buff | python | def to_string(self):
buff = u""
for child in self.content.iter():
if child.tag in [self.qn('text:p'), self.qn('text:h')]:
buff += self.text_to_string(child) + "\n"
# remove last newline char
if buff:
buff = buff[:-1]
return buff | [
"def",
"to_string",
"(",
"self",
")",
":",
"buff",
"=",
"u\"\"",
"for",
"child",
"in",
"self",
".",
"content",
".",
"iter",
"(",
")",
":",
"if",
"child",
".",
"tag",
"in",
"[",
"self",
".",
"qn",
"(",
"'text:p'",
")",
",",
"self",
".",
"qn",
"(... | Converts the document to a string. | [
"Converts",
"the",
"document",
"to",
"a",
"string",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/odt_parser.py#L19-L28 |
238,419 | deanmalmgren/textract | textract/parsers/odt_parser.py | Parser.qn | def qn(self, namespace):
"""Connect tag prefix to longer namespace"""
nsmap = {
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
}
spl = namespace.split(':')
return '{{{}}}{}'.format(nsmap[spl[0]], spl[1]) | python | def qn(self, namespace):
nsmap = {
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
}
spl = namespace.split(':')
return '{{{}}}{}'.format(nsmap[spl[0]], spl[1]) | [
"def",
"qn",
"(",
"self",
",",
"namespace",
")",
":",
"nsmap",
"=",
"{",
"'text'",
":",
"'urn:oasis:names:tc:opendocument:xmlns:text:1.0'",
",",
"}",
"spl",
"=",
"namespace",
".",
"split",
"(",
"':'",
")",
"return",
"'{{{}}}{}'",
".",
"format",
"(",
"nsmap",... | Connect tag prefix to longer namespace | [
"Connect",
"tag",
"prefix",
"to",
"longer",
"namespace"
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/odt_parser.py#L51-L57 |
238,420 | deanmalmgren/textract | textract/cli.py | get_parser | def get_parser():
"""Initialize the parser for the command line interface and bind the
autocompletion functionality"""
# initialize the parser
parser = argparse.ArgumentParser(
description=(
'Command line tool for extracting text from any document. '
) % locals(),
)
# define the command line options here
parser.add_argument(
'filename', help='Filename to extract text.',
).completer = argcomplete.completers.FilesCompleter
parser.add_argument(
'-e', '--encoding', type=str, default=DEFAULT_ENCODING,
choices=_get_available_encodings(),
help='Specify the encoding of the output.',
)
parser.add_argument(
'--extension', type=str, default=None,
choices=_get_available_extensions(),
help='Specify the extension of the file.',
)
parser.add_argument(
'-m', '--method', default='',
help='Specify a method of extraction for formats that support it',
)
parser.add_argument(
'-o', '--output', type=FileType('wb'), default='-',
help='Output raw text in this file',
)
parser.add_argument(
'-O', '--option', type=str, action=AddToNamespaceAction,
help=(
'Add arbitrary options to various parsers of the form '
'KEYWORD=VALUE. A full list of available KEYWORD options is '
'available at http://bit.ly/textract-options'
),
)
parser.add_argument(
'-v', '--version', action='version', version='%(prog)s '+VERSION,
)
# enable autocompletion with argcomplete
argcomplete.autocomplete(parser)
return parser | python | def get_parser():
# initialize the parser
parser = argparse.ArgumentParser(
description=(
'Command line tool for extracting text from any document. '
) % locals(),
)
# define the command line options here
parser.add_argument(
'filename', help='Filename to extract text.',
).completer = argcomplete.completers.FilesCompleter
parser.add_argument(
'-e', '--encoding', type=str, default=DEFAULT_ENCODING,
choices=_get_available_encodings(),
help='Specify the encoding of the output.',
)
parser.add_argument(
'--extension', type=str, default=None,
choices=_get_available_extensions(),
help='Specify the extension of the file.',
)
parser.add_argument(
'-m', '--method', default='',
help='Specify a method of extraction for formats that support it',
)
parser.add_argument(
'-o', '--output', type=FileType('wb'), default='-',
help='Output raw text in this file',
)
parser.add_argument(
'-O', '--option', type=str, action=AddToNamespaceAction,
help=(
'Add arbitrary options to various parsers of the form '
'KEYWORD=VALUE. A full list of available KEYWORD options is '
'available at http://bit.ly/textract-options'
),
)
parser.add_argument(
'-v', '--version', action='version', version='%(prog)s '+VERSION,
)
# enable autocompletion with argcomplete
argcomplete.autocomplete(parser)
return parser | [
"def",
"get_parser",
"(",
")",
":",
"# initialize the parser",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"(",
"'Command line tool for extracting text from any document. '",
")",
"%",
"locals",
"(",
")",
",",
")",
"# define the command li... | Initialize the parser for the command line interface and bind the
autocompletion functionality | [
"Initialize",
"the",
"parser",
"for",
"the",
"command",
"line",
"interface",
"and",
"bind",
"the",
"autocompletion",
"functionality"
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/cli.py#L45-L93 |
238,421 | deanmalmgren/textract | textract/cli.py | _get_available_encodings | def _get_available_encodings():
"""Get a list of the available encodings to make it easy to
tab-complete the command line interface.
Inspiration from http://stackoverflow.com/a/3824405/564709
"""
available_encodings = set(encodings.aliases.aliases.values())
paths = [os.path.dirname(encodings.__file__)]
for importer, modname, ispkg in pkgutil.walk_packages(path=paths):
available_encodings.add(modname)
available_encodings = list(available_encodings)
available_encodings.sort()
return available_encodings | python | def _get_available_encodings():
available_encodings = set(encodings.aliases.aliases.values())
paths = [os.path.dirname(encodings.__file__)]
for importer, modname, ispkg in pkgutil.walk_packages(path=paths):
available_encodings.add(modname)
available_encodings = list(available_encodings)
available_encodings.sort()
return available_encodings | [
"def",
"_get_available_encodings",
"(",
")",
":",
"available_encodings",
"=",
"set",
"(",
"encodings",
".",
"aliases",
".",
"aliases",
".",
"values",
"(",
")",
")",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"dirname",
"(",
"encodings",
".",
"__file__",
... | Get a list of the available encodings to make it easy to
tab-complete the command line interface.
Inspiration from http://stackoverflow.com/a/3824405/564709 | [
"Get",
"a",
"list",
"of",
"the",
"available",
"encodings",
"to",
"make",
"it",
"easy",
"to",
"tab",
"-",
"complete",
"the",
"command",
"line",
"interface",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/cli.py#L96-L108 |
238,422 | deanmalmgren/textract | textract/parsers/pdf_parser.py | Parser.extract_pdftotext | def extract_pdftotext(self, filename, **kwargs):
"""Extract text from pdfs using the pdftotext command line utility."""
if 'layout' in kwargs:
args = ['pdftotext', '-layout', filename, '-']
else:
args = ['pdftotext', filename, '-']
stdout, _ = self.run(args)
return stdout | python | def extract_pdftotext(self, filename, **kwargs):
if 'layout' in kwargs:
args = ['pdftotext', '-layout', filename, '-']
else:
args = ['pdftotext', filename, '-']
stdout, _ = self.run(args)
return stdout | [
"def",
"extract_pdftotext",
"(",
"self",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'layout'",
"in",
"kwargs",
":",
"args",
"=",
"[",
"'pdftotext'",
",",
"'-layout'",
",",
"filename",
",",
"'-'",
"]",
"else",
":",
"args",
"=",
"[",
"'... | Extract text from pdfs using the pdftotext command line utility. | [
"Extract",
"text",
"from",
"pdfs",
"using",
"the",
"pdftotext",
"command",
"line",
"utility",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/pdf_parser.py#L37-L44 |
238,423 | deanmalmgren/textract | textract/parsers/pdf_parser.py | Parser.extract_pdfminer | def extract_pdfminer(self, filename, **kwargs):
"""Extract text from pdfs using pdfminer."""
stdout, _ = self.run(['pdf2txt.py', filename])
return stdout | python | def extract_pdfminer(self, filename, **kwargs):
stdout, _ = self.run(['pdf2txt.py', filename])
return stdout | [
"def",
"extract_pdfminer",
"(",
"self",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"stdout",
",",
"_",
"=",
"self",
".",
"run",
"(",
"[",
"'pdf2txt.py'",
",",
"filename",
"]",
")",
"return",
"stdout"
] | Extract text from pdfs using pdfminer. | [
"Extract",
"text",
"from",
"pdfs",
"using",
"pdfminer",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/pdf_parser.py#L46-L49 |
238,424 | deanmalmgren/textract | textract/parsers/audio.py | Parser.convert_to_wav | def convert_to_wav(self, filename):
"""
Uses sox cmdline tool, to convert audio file to .wav
Note: for testing, use -
http://www.text2speech.org/,
with American Male 2 for best results
"""
temp_filename = '{0}.wav'.format(self.temp_filename())
self.run(['sox', '-G', '-c', '1', filename, temp_filename])
return temp_filename | python | def convert_to_wav(self, filename):
temp_filename = '{0}.wav'.format(self.temp_filename())
self.run(['sox', '-G', '-c', '1', filename, temp_filename])
return temp_filename | [
"def",
"convert_to_wav",
"(",
"self",
",",
"filename",
")",
":",
"temp_filename",
"=",
"'{0}.wav'",
".",
"format",
"(",
"self",
".",
"temp_filename",
"(",
")",
")",
"self",
".",
"run",
"(",
"[",
"'sox'",
",",
"'-G'",
",",
"'-c'",
",",
"'1'",
",",
"fi... | Uses sox cmdline tool, to convert audio file to .wav
Note: for testing, use -
http://www.text2speech.org/,
with American Male 2 for best results | [
"Uses",
"sox",
"cmdline",
"tool",
"to",
"convert",
"audio",
"file",
"to",
".",
"wav"
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/audio.py#L56-L66 |
238,425 | deanmalmgren/textract | textract/parsers/html_parser.py | Parser._visible | def _visible(self, element):
"""Used to filter text elements that have invisible text on the page.
"""
if element.name in self._disallowed_names:
return False
elif re.match(u'<!--.*-->', six.text_type(element.extract())):
return False
return True | python | def _visible(self, element):
if element.name in self._disallowed_names:
return False
elif re.match(u'<!--.*-->', six.text_type(element.extract())):
return False
return True | [
"def",
"_visible",
"(",
"self",
",",
"element",
")",
":",
"if",
"element",
".",
"name",
"in",
"self",
".",
"_disallowed_names",
":",
"return",
"False",
"elif",
"re",
".",
"match",
"(",
"u'<!--.*-->'",
",",
"six",
".",
"text_type",
"(",
"element",
".",
... | Used to filter text elements that have invisible text on the page. | [
"Used",
"to",
"filter",
"text",
"elements",
"that",
"have",
"invisible",
"text",
"on",
"the",
"page",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L27-L34 |
238,426 | deanmalmgren/textract | textract/parsers/html_parser.py | Parser._find_any_text | def _find_any_text(self, tag):
"""Looks for any possible text within given tag.
"""
text = ''
if tag is not None:
text = six.text_type(tag)
text = re.sub(r'(<[^>]+>)', '', text)
text = re.sub(r'\s', ' ', text)
text = text.strip()
return text | python | def _find_any_text(self, tag):
text = ''
if tag is not None:
text = six.text_type(tag)
text = re.sub(r'(<[^>]+>)', '', text)
text = re.sub(r'\s', ' ', text)
text = text.strip()
return text | [
"def",
"_find_any_text",
"(",
"self",
",",
"tag",
")",
":",
"text",
"=",
"''",
"if",
"tag",
"is",
"not",
"None",
":",
"text",
"=",
"six",
".",
"text_type",
"(",
"tag",
")",
"text",
"=",
"re",
".",
"sub",
"(",
"r'(<[^>]+>)'",
",",
"''",
",",
"text... | Looks for any possible text within given tag. | [
"Looks",
"for",
"any",
"possible",
"text",
"within",
"given",
"tag",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L44-L53 |
238,427 | deanmalmgren/textract | textract/parsers/html_parser.py | Parser._join_inlines | def _join_inlines(self, soup):
"""Unwraps inline elements defined in self._inline_tags.
"""
elements = soup.find_all(True)
for elem in elements:
if self._inline(elem):
elem.unwrap()
return soup | python | def _join_inlines(self, soup):
elements = soup.find_all(True)
for elem in elements:
if self._inline(elem):
elem.unwrap()
return soup | [
"def",
"_join_inlines",
"(",
"self",
",",
"soup",
")",
":",
"elements",
"=",
"soup",
".",
"find_all",
"(",
"True",
")",
"for",
"elem",
"in",
"elements",
":",
"if",
"self",
".",
"_inline",
"(",
"elem",
")",
":",
"elem",
".",
"unwrap",
"(",
")",
"ret... | Unwraps inline elements defined in self._inline_tags. | [
"Unwraps",
"inline",
"elements",
"defined",
"in",
"self",
".",
"_inline_tags",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L118-L125 |
238,428 | deanmalmgren/textract | textract/parsers/utils.py | ShellParser.temp_filename | def temp_filename(self):
"""Return a unique tempfile name.
"""
# TODO: it would be nice to get this to behave more like a
# context so we can make sure these temporary files are
# removed, regardless of whether an error occurs or the
# program is terminated.
handle, filename = tempfile.mkstemp()
os.close(handle)
return filename | python | def temp_filename(self):
# TODO: it would be nice to get this to behave more like a
# context so we can make sure these temporary files are
# removed, regardless of whether an error occurs or the
# program is terminated.
handle, filename = tempfile.mkstemp()
os.close(handle)
return filename | [
"def",
"temp_filename",
"(",
"self",
")",
":",
"# TODO: it would be nice to get this to behave more like a",
"# context so we can make sure these temporary files are",
"# removed, regardless of whether an error occurs or the",
"# program is terminated.",
"handle",
",",
"filename",
"=",
"... | Return a unique tempfile name. | [
"Return",
"a",
"unique",
"tempfile",
"name",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/utils.py#L106-L115 |
238,429 | deanmalmgren/textract | textract/parsers/__init__.py | process | def process(filename, encoding=DEFAULT_ENCODING, extension=None, **kwargs):
"""This is the core function used for extracting text. It routes the
``filename`` to the appropriate parser and returns the extracted
text as a byte-string encoded with ``encoding``.
"""
# make sure the filename exists
if not os.path.exists(filename):
raise exceptions.MissingFileError(filename)
# get the filename extension, which is something like .docx for
# example, and import the module dynamically using importlib. This
# is a relative import so the name of the package is necessary
# normally, file extension will be extracted from the file name
# if the file name has no extension, then the user can pass the
# extension as an argument
if extension:
ext = extension
# check if the extension has the leading .
if not ext.startswith('.'):
ext = '.' + ext
ext = ext.lower()
else:
_, ext = os.path.splitext(filename)
ext = ext.lower()
# check the EXTENSION_SYNONYMS dictionary
ext = EXTENSION_SYNONYMS.get(ext, ext)
# to avoid conflicts with packages that are installed globally
# (e.g. python's json module), all extension parser modules have
# the _parser extension
rel_module = ext + _FILENAME_SUFFIX
# If we can't import the module, the file extension isn't currently
# supported
try:
filetype_module = importlib.import_module(
rel_module, 'textract.parsers'
)
except ImportError:
raise exceptions.ExtensionNotSupported(ext)
# do the extraction
parser = filetype_module.Parser()
return parser.process(filename, encoding, **kwargs) | python | def process(filename, encoding=DEFAULT_ENCODING, extension=None, **kwargs):
# make sure the filename exists
if not os.path.exists(filename):
raise exceptions.MissingFileError(filename)
# get the filename extension, which is something like .docx for
# example, and import the module dynamically using importlib. This
# is a relative import so the name of the package is necessary
# normally, file extension will be extracted from the file name
# if the file name has no extension, then the user can pass the
# extension as an argument
if extension:
ext = extension
# check if the extension has the leading .
if not ext.startswith('.'):
ext = '.' + ext
ext = ext.lower()
else:
_, ext = os.path.splitext(filename)
ext = ext.lower()
# check the EXTENSION_SYNONYMS dictionary
ext = EXTENSION_SYNONYMS.get(ext, ext)
# to avoid conflicts with packages that are installed globally
# (e.g. python's json module), all extension parser modules have
# the _parser extension
rel_module = ext + _FILENAME_SUFFIX
# If we can't import the module, the file extension isn't currently
# supported
try:
filetype_module = importlib.import_module(
rel_module, 'textract.parsers'
)
except ImportError:
raise exceptions.ExtensionNotSupported(ext)
# do the extraction
parser = filetype_module.Parser()
return parser.process(filename, encoding, **kwargs) | [
"def",
"process",
"(",
"filename",
",",
"encoding",
"=",
"DEFAULT_ENCODING",
",",
"extension",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# make sure the filename exists",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"rai... | This is the core function used for extracting text. It routes the
``filename`` to the appropriate parser and returns the extracted
text as a byte-string encoded with ``encoding``. | [
"This",
"is",
"the",
"core",
"function",
"used",
"for",
"extracting",
"text",
".",
"It",
"routes",
"the",
"filename",
"to",
"the",
"appropriate",
"parser",
"and",
"returns",
"the",
"extracted",
"text",
"as",
"a",
"byte",
"-",
"string",
"encoded",
"with",
"... | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/__init__.py#L31-L77 |
238,430 | deanmalmgren/textract | textract/parsers/__init__.py | _get_available_extensions | def _get_available_extensions():
"""Get a list of available file extensions to make it easy for
tab-completion and exception handling.
"""
extensions = []
# from filenames
parsers_dir = os.path.join(os.path.dirname(__file__))
glob_filename = os.path.join(parsers_dir, "*" + _FILENAME_SUFFIX + ".py")
ext_re = re.compile(glob_filename.replace('*', "(?P<ext>\w+)"))
for filename in glob.glob(glob_filename):
ext_match = ext_re.match(filename)
ext = ext_match.groups()[0]
extensions.append(ext)
extensions.append('.' + ext)
# from relevant synonyms (don't use the '' synonym)
for ext in EXTENSION_SYNONYMS.keys():
if ext:
extensions.append(ext)
extensions.append(ext.replace('.', '', 1))
extensions.sort()
return extensions | python | def _get_available_extensions():
extensions = []
# from filenames
parsers_dir = os.path.join(os.path.dirname(__file__))
glob_filename = os.path.join(parsers_dir, "*" + _FILENAME_SUFFIX + ".py")
ext_re = re.compile(glob_filename.replace('*', "(?P<ext>\w+)"))
for filename in glob.glob(glob_filename):
ext_match = ext_re.match(filename)
ext = ext_match.groups()[0]
extensions.append(ext)
extensions.append('.' + ext)
# from relevant synonyms (don't use the '' synonym)
for ext in EXTENSION_SYNONYMS.keys():
if ext:
extensions.append(ext)
extensions.append(ext.replace('.', '', 1))
extensions.sort()
return extensions | [
"def",
"_get_available_extensions",
"(",
")",
":",
"extensions",
"=",
"[",
"]",
"# from filenames",
"parsers_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"glob_filename",
"=",
"os",
".",
"p... | Get a list of available file extensions to make it easy for
tab-completion and exception handling. | [
"Get",
"a",
"list",
"of",
"available",
"file",
"extensions",
"to",
"make",
"it",
"easy",
"for",
"tab",
"-",
"completion",
"and",
"exception",
"handling",
"."
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/__init__.py#L80-L102 |
238,431 | deanmalmgren/textract | setup.py | parse_requirements | def parse_requirements(requirements_filename):
"""read in the dependencies from the requirements files
"""
dependencies, dependency_links = [], []
requirements_dir = os.path.dirname(requirements_filename)
with open(requirements_filename, 'r') as stream:
for line in stream:
line = line.strip()
if line.startswith("-r"):
filename = os.path.join(requirements_dir, line[2:].strip())
_dependencies, _dependency_links = parse_requirements(filename)
dependencies.extend(_dependencies)
dependency_links.extend(_dependency_links)
elif line.startswith("http"):
dependency_links.append(line)
else:
package = line.split('#')[0]
if package:
dependencies.append(package)
return dependencies, dependency_links | python | def parse_requirements(requirements_filename):
dependencies, dependency_links = [], []
requirements_dir = os.path.dirname(requirements_filename)
with open(requirements_filename, 'r') as stream:
for line in stream:
line = line.strip()
if line.startswith("-r"):
filename = os.path.join(requirements_dir, line[2:].strip())
_dependencies, _dependency_links = parse_requirements(filename)
dependencies.extend(_dependencies)
dependency_links.extend(_dependency_links)
elif line.startswith("http"):
dependency_links.append(line)
else:
package = line.split('#')[0]
if package:
dependencies.append(package)
return dependencies, dependency_links | [
"def",
"parse_requirements",
"(",
"requirements_filename",
")",
":",
"dependencies",
",",
"dependency_links",
"=",
"[",
"]",
",",
"[",
"]",
"requirements_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"requirements_filename",
")",
"with",
"open",
"(",
"req... | read in the dependencies from the requirements files | [
"read",
"in",
"the",
"dependencies",
"from",
"the",
"requirements",
"files"
] | 117ea191d93d80321e4bf01f23cc1ac54d69a075 | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/setup.py#L18-L37 |
238,432 | lyst/lightfm | lightfm/data.py | Dataset.build_interactions | def build_interactions(self, data):
"""
Build an interaction matrix.
Two matrices will be returned: a (num_users, num_items)
COO matrix with interactions, and a (num_users, num_items)
matrix with the corresponding interaction weights.
Parameters
----------
data: iterable of (user_id, item_id) or (user_id, item_id, weight)
An iterable of interactions. The user and item ids will be
translated to internal model indices using the mappings
constructed during the fit call. If weights are not provided
they will be assumed to be 1.0.
Returns
-------
(interactions, weights): COO matrix, COO matrix
Two COO matrices: the interactions matrix
and the corresponding weights matrix.
"""
interactions = _IncrementalCOOMatrix(self.interactions_shape(), np.int32)
weights = _IncrementalCOOMatrix(self.interactions_shape(), np.float32)
for datum in data:
user_idx, item_idx, weight = self._unpack_datum(datum)
interactions.append(user_idx, item_idx, 1)
weights.append(user_idx, item_idx, weight)
return (interactions.tocoo(), weights.tocoo()) | python | def build_interactions(self, data):
interactions = _IncrementalCOOMatrix(self.interactions_shape(), np.int32)
weights = _IncrementalCOOMatrix(self.interactions_shape(), np.float32)
for datum in data:
user_idx, item_idx, weight = self._unpack_datum(datum)
interactions.append(user_idx, item_idx, 1)
weights.append(user_idx, item_idx, weight)
return (interactions.tocoo(), weights.tocoo()) | [
"def",
"build_interactions",
"(",
"self",
",",
"data",
")",
":",
"interactions",
"=",
"_IncrementalCOOMatrix",
"(",
"self",
".",
"interactions_shape",
"(",
")",
",",
"np",
".",
"int32",
")",
"weights",
"=",
"_IncrementalCOOMatrix",
"(",
"self",
".",
"interacti... | Build an interaction matrix.
Two matrices will be returned: a (num_users, num_items)
COO matrix with interactions, and a (num_users, num_items)
matrix with the corresponding interaction weights.
Parameters
----------
data: iterable of (user_id, item_id) or (user_id, item_id, weight)
An iterable of interactions. The user and item ids will be
translated to internal model indices using the mappings
constructed during the fit call. If weights are not provided
they will be assumed to be 1.0.
Returns
-------
(interactions, weights): COO matrix, COO matrix
Two COO matrices: the interactions matrix
and the corresponding weights matrix. | [
"Build",
"an",
"interaction",
"matrix",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/data.py#L292-L326 |
238,433 | lyst/lightfm | lightfm/data.py | Dataset.mapping | def mapping(self):
"""
Return the constructed mappings.
Invert these to map internal indices to external ids.
Returns
-------
(user id map, user feature map, item id map, item id map): tuple of dictionaries
"""
return (
self._user_id_mapping,
self._user_feature_mapping,
self._item_id_mapping,
self._item_feature_mapping,
) | python | def mapping(self):
return (
self._user_id_mapping,
self._user_feature_mapping,
self._item_id_mapping,
self._item_feature_mapping,
) | [
"def",
"mapping",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_user_id_mapping",
",",
"self",
".",
"_user_feature_mapping",
",",
"self",
".",
"_item_id_mapping",
",",
"self",
".",
"_item_feature_mapping",
",",
")"
] | Return the constructed mappings.
Invert these to map internal indices to external ids.
Returns
-------
(user id map, user feature map, item id map, item id map): tuple of dictionaries | [
"Return",
"the",
"constructed",
"mappings",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/data.py#L428-L445 |
238,434 | lyst/lightfm | examples/movielens/data.py | _get_movielens_path | def _get_movielens_path():
"""
Get path to the movielens dataset file.
"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'movielens.zip') | python | def _get_movielens_path():
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'movielens.zip') | [
"def",
"_get_movielens_path",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
",",
"'movielens.zip'",
")"
] | Get path to the movielens dataset file. | [
"Get",
"path",
"to",
"the",
"movielens",
"dataset",
"file",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/examples/movielens/data.py#L12-L18 |
238,435 | lyst/lightfm | examples/movielens/data.py | _download_movielens | def _download_movielens(dest_path):
"""
Download the dataset.
"""
url = 'http://files.grouplens.org/datasets/movielens/ml-100k.zip'
req = requests.get(url, stream=True)
with open(dest_path, 'wb') as fd:
for chunk in req.iter_content():
fd.write(chunk) | python | def _download_movielens(dest_path):
url = 'http://files.grouplens.org/datasets/movielens/ml-100k.zip'
req = requests.get(url, stream=True)
with open(dest_path, 'wb') as fd:
for chunk in req.iter_content():
fd.write(chunk) | [
"def",
"_download_movielens",
"(",
"dest_path",
")",
":",
"url",
"=",
"'http://files.grouplens.org/datasets/movielens/ml-100k.zip'",
"req",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"with",
"open",
"(",
"dest_path",
",",
"'wb'",
"... | Download the dataset. | [
"Download",
"the",
"dataset",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/examples/movielens/data.py#L21-L31 |
238,436 | lyst/lightfm | examples/movielens/data.py | _get_movie_raw_metadata | def _get_movie_raw_metadata():
"""
Get raw lines of the genre file.
"""
path = _get_movielens_path()
if not os.path.isfile(path):
_download_movielens(path)
with zipfile.ZipFile(path) as datafile:
return datafile.read('ml-100k/u.item').decode(errors='ignore').split('\n') | python | def _get_movie_raw_metadata():
path = _get_movielens_path()
if not os.path.isfile(path):
_download_movielens(path)
with zipfile.ZipFile(path) as datafile:
return datafile.read('ml-100k/u.item').decode(errors='ignore').split('\n') | [
"def",
"_get_movie_raw_metadata",
"(",
")",
":",
"path",
"=",
"_get_movielens_path",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"_download_movielens",
"(",
"path",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"path",
... | Get raw lines of the genre file. | [
"Get",
"raw",
"lines",
"of",
"the",
"genre",
"file",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/examples/movielens/data.py#L82-L93 |
238,437 | lyst/lightfm | lightfm/lightfm.py | LightFM._initialize | def _initialize(self, no_components, no_item_features, no_user_features):
"""
Initialise internal latent representations.
"""
# Initialise item features.
self.item_embeddings = (
(self.random_state.rand(no_item_features, no_components) - 0.5)
/ no_components
).astype(np.float32)
self.item_embedding_gradients = np.zeros_like(self.item_embeddings)
self.item_embedding_momentum = np.zeros_like(self.item_embeddings)
self.item_biases = np.zeros(no_item_features, dtype=np.float32)
self.item_bias_gradients = np.zeros_like(self.item_biases)
self.item_bias_momentum = np.zeros_like(self.item_biases)
# Initialise user features.
self.user_embeddings = (
(self.random_state.rand(no_user_features, no_components) - 0.5)
/ no_components
).astype(np.float32)
self.user_embedding_gradients = np.zeros_like(self.user_embeddings)
self.user_embedding_momentum = np.zeros_like(self.user_embeddings)
self.user_biases = np.zeros(no_user_features, dtype=np.float32)
self.user_bias_gradients = np.zeros_like(self.user_biases)
self.user_bias_momentum = np.zeros_like(self.user_biases)
if self.learning_schedule == "adagrad":
self.item_embedding_gradients += 1
self.item_bias_gradients += 1
self.user_embedding_gradients += 1
self.user_bias_gradients += 1 | python | def _initialize(self, no_components, no_item_features, no_user_features):
# Initialise item features.
self.item_embeddings = (
(self.random_state.rand(no_item_features, no_components) - 0.5)
/ no_components
).astype(np.float32)
self.item_embedding_gradients = np.zeros_like(self.item_embeddings)
self.item_embedding_momentum = np.zeros_like(self.item_embeddings)
self.item_biases = np.zeros(no_item_features, dtype=np.float32)
self.item_bias_gradients = np.zeros_like(self.item_biases)
self.item_bias_momentum = np.zeros_like(self.item_biases)
# Initialise user features.
self.user_embeddings = (
(self.random_state.rand(no_user_features, no_components) - 0.5)
/ no_components
).astype(np.float32)
self.user_embedding_gradients = np.zeros_like(self.user_embeddings)
self.user_embedding_momentum = np.zeros_like(self.user_embeddings)
self.user_biases = np.zeros(no_user_features, dtype=np.float32)
self.user_bias_gradients = np.zeros_like(self.user_biases)
self.user_bias_momentum = np.zeros_like(self.user_biases)
if self.learning_schedule == "adagrad":
self.item_embedding_gradients += 1
self.item_bias_gradients += 1
self.user_embedding_gradients += 1
self.user_bias_gradients += 1 | [
"def",
"_initialize",
"(",
"self",
",",
"no_components",
",",
"no_item_features",
",",
"no_user_features",
")",
":",
"# Initialise item features.",
"self",
".",
"item_embeddings",
"=",
"(",
"(",
"self",
".",
"random_state",
".",
"rand",
"(",
"no_item_features",
",... | Initialise internal latent representations. | [
"Initialise",
"internal",
"latent",
"representations",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L264-L295 |
238,438 | lyst/lightfm | lightfm/lightfm.py | LightFM._run_epoch | def _run_epoch(
self,
item_features,
user_features,
interactions,
sample_weight,
num_threads,
loss,
):
"""
Run an individual epoch.
"""
if loss in ("warp", "bpr", "warp-kos"):
# The CSR conversion needs to happen before shuffle indices are created.
# Calling .tocsr may result in a change in the data arrays of the COO matrix,
positives_lookup = CSRMatrix(
self._get_positives_lookup_matrix(interactions)
)
# Create shuffle indexes.
shuffle_indices = np.arange(len(interactions.data), dtype=np.int32)
self.random_state.shuffle(shuffle_indices)
lightfm_data = self._get_lightfm_data()
# Call the estimation routines.
if loss == "warp":
fit_warp(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
self.random_state,
)
elif loss == "bpr":
fit_bpr(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
self.random_state,
)
elif loss == "warp-kos":
fit_warp_kos(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
self.k,
self.n,
num_threads,
self.random_state,
)
else:
fit_logistic(
CSRMatrix(item_features),
CSRMatrix(user_features),
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
) | python | def _run_epoch(
self,
item_features,
user_features,
interactions,
sample_weight,
num_threads,
loss,
):
if loss in ("warp", "bpr", "warp-kos"):
# The CSR conversion needs to happen before shuffle indices are created.
# Calling .tocsr may result in a change in the data arrays of the COO matrix,
positives_lookup = CSRMatrix(
self._get_positives_lookup_matrix(interactions)
)
# Create shuffle indexes.
shuffle_indices = np.arange(len(interactions.data), dtype=np.int32)
self.random_state.shuffle(shuffle_indices)
lightfm_data = self._get_lightfm_data()
# Call the estimation routines.
if loss == "warp":
fit_warp(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
self.random_state,
)
elif loss == "bpr":
fit_bpr(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
self.random_state,
)
elif loss == "warp-kos":
fit_warp_kos(
CSRMatrix(item_features),
CSRMatrix(user_features),
positives_lookup,
interactions.row,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
self.k,
self.n,
num_threads,
self.random_state,
)
else:
fit_logistic(
CSRMatrix(item_features),
CSRMatrix(user_features),
interactions.row,
interactions.col,
interactions.data,
sample_weight,
shuffle_indices,
lightfm_data,
self.learning_rate,
self.item_alpha,
self.user_alpha,
num_threads,
) | [
"def",
"_run_epoch",
"(",
"self",
",",
"item_features",
",",
"user_features",
",",
"interactions",
",",
"sample_weight",
",",
"num_threads",
",",
"loss",
",",
")",
":",
"if",
"loss",
"in",
"(",
"\"warp\"",
",",
"\"bpr\"",
",",
"\"warp-kos\"",
")",
":",
"# ... | Run an individual epoch. | [
"Run",
"an",
"individual",
"epoch",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L651-L742 |
238,439 | lyst/lightfm | lightfm/lightfm.py | LightFM.predict | def predict(
self, user_ids, item_ids, item_features=None, user_features=None, num_threads=1
):
"""
Compute the recommendation score for user-item pairs.
For details on how to use feature matrices, see the documentation
on the :class:`lightfm.LightFM` class.
Arguments
---------
user_ids: integer or np.int32 array of shape [n_pairs,]
single user id or an array containing the user ids for the
user-item pairs for which a prediction is to be computed. Note
that these are LightFM's internal id's, i.e. the index of the
user in the interaction matrix used for fitting the model.
item_ids: np.int32 array of shape [n_pairs,]
an array containing the item ids for the user-item pairs for which
a prediction is to be computed. Note that these are LightFM's
internal id's, i.e. the index of the item in the interaction
matrix used for fitting the model.
user_features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over features.
item_features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
num_threads: int, optional
Number of parallel computation threads to use. Should
not be higher than the number of physical cores.
Returns
-------
np.float32 array of shape [n_pairs,]
Numpy array containing the recommendation scores for pairs defined
by the inputs.
"""
self._check_initialized()
if not isinstance(user_ids, np.ndarray):
user_ids = np.repeat(np.int32(user_ids), len(item_ids))
if isinstance(item_ids, (list, tuple)):
item_ids = np.array(item_ids, dtype=np.int32)
assert len(user_ids) == len(item_ids)
if user_ids.dtype != np.int32:
user_ids = user_ids.astype(np.int32)
if item_ids.dtype != np.int32:
item_ids = item_ids.astype(np.int32)
if num_threads < 1:
raise ValueError("Number of threads must be 1 or larger.")
if user_ids.min() < 0 or item_ids.min() < 0:
raise ValueError(
"User or item ids cannot be negative. "
"Check your inputs for negative numbers "
"or very large numbers that can overflow."
)
n_users = user_ids.max() + 1
n_items = item_ids.max() + 1
(user_features, item_features) = self._construct_feature_matrices(
n_users, n_items, user_features, item_features
)
lightfm_data = self._get_lightfm_data()
predictions = np.empty(len(user_ids), dtype=np.float64)
predict_lightfm(
CSRMatrix(item_features),
CSRMatrix(user_features),
user_ids,
item_ids,
predictions,
lightfm_data,
num_threads,
)
return predictions | python | def predict(
self, user_ids, item_ids, item_features=None, user_features=None, num_threads=1
):
self._check_initialized()
if not isinstance(user_ids, np.ndarray):
user_ids = np.repeat(np.int32(user_ids), len(item_ids))
if isinstance(item_ids, (list, tuple)):
item_ids = np.array(item_ids, dtype=np.int32)
assert len(user_ids) == len(item_ids)
if user_ids.dtype != np.int32:
user_ids = user_ids.astype(np.int32)
if item_ids.dtype != np.int32:
item_ids = item_ids.astype(np.int32)
if num_threads < 1:
raise ValueError("Number of threads must be 1 or larger.")
if user_ids.min() < 0 or item_ids.min() < 0:
raise ValueError(
"User or item ids cannot be negative. "
"Check your inputs for negative numbers "
"or very large numbers that can overflow."
)
n_users = user_ids.max() + 1
n_items = item_ids.max() + 1
(user_features, item_features) = self._construct_feature_matrices(
n_users, n_items, user_features, item_features
)
lightfm_data = self._get_lightfm_data()
predictions = np.empty(len(user_ids), dtype=np.float64)
predict_lightfm(
CSRMatrix(item_features),
CSRMatrix(user_features),
user_ids,
item_ids,
predictions,
lightfm_data,
num_threads,
)
return predictions | [
"def",
"predict",
"(",
"self",
",",
"user_ids",
",",
"item_ids",
",",
"item_features",
"=",
"None",
",",
"user_features",
"=",
"None",
",",
"num_threads",
"=",
"1",
")",
":",
"self",
".",
"_check_initialized",
"(",
")",
"if",
"not",
"isinstance",
"(",
"u... | Compute the recommendation score for user-item pairs.
For details on how to use feature matrices, see the documentation
on the :class:`lightfm.LightFM` class.
Arguments
---------
user_ids: integer or np.int32 array of shape [n_pairs,]
single user id or an array containing the user ids for the
user-item pairs for which a prediction is to be computed. Note
that these are LightFM's internal id's, i.e. the index of the
user in the interaction matrix used for fitting the model.
item_ids: np.int32 array of shape [n_pairs,]
an array containing the item ids for the user-item pairs for which
a prediction is to be computed. Note that these are LightFM's
internal id's, i.e. the index of the item in the interaction
matrix used for fitting the model.
user_features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over features.
item_features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
num_threads: int, optional
Number of parallel computation threads to use. Should
not be higher than the number of physical cores.
Returns
-------
np.float32 array of shape [n_pairs,]
Numpy array containing the recommendation scores for pairs defined
by the inputs. | [
"Compute",
"the",
"recommendation",
"score",
"for",
"user",
"-",
"item",
"pairs",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L744-L828 |
238,440 | lyst/lightfm | lightfm/lightfm.py | LightFM.get_item_representations | def get_item_representations(self, features=None):
"""
Get the latent representations for items given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
An identity matrix will be used if not supplied.
Returns
-------
(item_biases, item_embeddings):
(np.float32 array of shape n_items,
np.float32 array of shape [n_items, num_components]
Biases and latent representations for items.
"""
self._check_initialized()
if features is None:
return self.item_biases, self.item_embeddings
features = sp.csr_matrix(features, dtype=CYTHON_DTYPE)
return features * self.item_biases, features * self.item_embeddings | python | def get_item_representations(self, features=None):
self._check_initialized()
if features is None:
return self.item_biases, self.item_embeddings
features = sp.csr_matrix(features, dtype=CYTHON_DTYPE)
return features * self.item_biases, features * self.item_embeddings | [
"def",
"get_item_representations",
"(",
"self",
",",
"features",
"=",
"None",
")",
":",
"self",
".",
"_check_initialized",
"(",
")",
"if",
"features",
"is",
"None",
":",
"return",
"self",
".",
"item_biases",
",",
"self",
".",
"item_embeddings",
"features",
"... | Get the latent representations for items given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
Each row contains that item's weights over features.
An identity matrix will be used if not supplied.
Returns
-------
(item_biases, item_embeddings):
(np.float32 array of shape n_items,
np.float32 array of shape [n_items, num_components]
Biases and latent representations for items. | [
"Get",
"the",
"latent",
"representations",
"for",
"items",
"given",
"model",
"and",
"features",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L947-L974 |
238,441 | lyst/lightfm | lightfm/lightfm.py | LightFM.get_user_representations | def get_user_representations(self, features=None):
"""
Get the latent representations for users given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over features.
An identity matrix will be used if not supplied.
Returns
-------
(user_biases, user_embeddings):
(np.float32 array of shape n_users
np.float32 array of shape [n_users, num_components]
Biases and latent representations for users.
"""
self._check_initialized()
if features is None:
return self.user_biases, self.user_embeddings
features = sp.csr_matrix(features, dtype=CYTHON_DTYPE)
return features * self.user_biases, features * self.user_embeddings | python | def get_user_representations(self, features=None):
self._check_initialized()
if features is None:
return self.user_biases, self.user_embeddings
features = sp.csr_matrix(features, dtype=CYTHON_DTYPE)
return features * self.user_biases, features * self.user_embeddings | [
"def",
"get_user_representations",
"(",
"self",
",",
"features",
"=",
"None",
")",
":",
"self",
".",
"_check_initialized",
"(",
")",
"if",
"features",
"is",
"None",
":",
"return",
"self",
".",
"user_biases",
",",
"self",
".",
"user_embeddings",
"features",
"... | Get the latent representations for users given model and features.
Arguments
---------
features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
Each row contains that user's weights over features.
An identity matrix will be used if not supplied.
Returns
-------
(user_biases, user_embeddings):
(np.float32 array of shape n_users
np.float32 array of shape [n_users, num_components]
Biases and latent representations for users. | [
"Get",
"the",
"latent",
"representations",
"for",
"users",
"given",
"model",
"and",
"features",
"."
] | 87b942f87759b8336f9066a25e4762ae7d95455e | https://github.com/lyst/lightfm/blob/87b942f87759b8336f9066a25e4762ae7d95455e/lightfm/lightfm.py#L976-L1003 |
238,442 | quantopian/empyrical | empyrical/stats.py | _adjust_returns | def _adjust_returns(returns, adjustment_factor):
"""
Returns the returns series adjusted by adjustment_factor. Optimizes for the
case of adjustment_factor being 0 by returning returns itself, not a copy!
Parameters
----------
returns : pd.Series or np.ndarray
adjustment_factor : pd.Series or np.ndarray or float or int
Returns
-------
adjusted_returns : array-like
"""
if isinstance(adjustment_factor, (float, int)) and adjustment_factor == 0:
return returns
return returns - adjustment_factor | python | def _adjust_returns(returns, adjustment_factor):
if isinstance(adjustment_factor, (float, int)) and adjustment_factor == 0:
return returns
return returns - adjustment_factor | [
"def",
"_adjust_returns",
"(",
"returns",
",",
"adjustment_factor",
")",
":",
"if",
"isinstance",
"(",
"adjustment_factor",
",",
"(",
"float",
",",
"int",
")",
")",
"and",
"adjustment_factor",
"==",
"0",
":",
"return",
"returns",
"return",
"returns",
"-",
"a... | Returns the returns series adjusted by adjustment_factor. Optimizes for the
case of adjustment_factor being 0 by returning returns itself, not a copy!
Parameters
----------
returns : pd.Series or np.ndarray
adjustment_factor : pd.Series or np.ndarray or float or int
Returns
-------
adjusted_returns : array-like | [
"Returns",
"the",
"returns",
"series",
"adjusted",
"by",
"adjustment_factor",
".",
"Optimizes",
"for",
"the",
"case",
"of",
"adjustment_factor",
"being",
"0",
"by",
"returning",
"returns",
"itself",
"not",
"a",
"copy!"
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L127-L143 |
238,443 | quantopian/empyrical | empyrical/stats.py | annualization_factor | def annualization_factor(period, annualization):
"""
Return annualization factor from period entered or if a custom
value is passed in.
Parameters
----------
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
annualization_factor : float
"""
if annualization is None:
try:
factor = ANNUALIZATION_FACTORS[period]
except KeyError:
raise ValueError(
"Period cannot be '{}'. "
"Can be '{}'.".format(
period, "', '".join(ANNUALIZATION_FACTORS.keys())
)
)
else:
factor = annualization
return factor | python | def annualization_factor(period, annualization):
if annualization is None:
try:
factor = ANNUALIZATION_FACTORS[period]
except KeyError:
raise ValueError(
"Period cannot be '{}'. "
"Can be '{}'.".format(
period, "', '".join(ANNUALIZATION_FACTORS.keys())
)
)
else:
factor = annualization
return factor | [
"def",
"annualization_factor",
"(",
"period",
",",
"annualization",
")",
":",
"if",
"annualization",
"is",
"None",
":",
"try",
":",
"factor",
"=",
"ANNUALIZATION_FACTORS",
"[",
"period",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"Period canno... | Return annualization factor from period entered or if a custom
value is passed in.
Parameters
----------
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
annualization_factor : float | [
"Return",
"annualization",
"factor",
"from",
"period",
"entered",
"or",
"if",
"a",
"custom",
"value",
"is",
"passed",
"in",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L146-L183 |
238,444 | quantopian/empyrical | empyrical/stats.py | simple_returns | def simple_returns(prices):
"""
Compute simple returns from a timeseries of prices.
Parameters
----------
prices : pd.Series, pd.DataFrame or np.ndarray
Prices of assets in wide-format, with assets as columns,
and indexed by datetimes.
Returns
-------
returns : array-like
Returns of assets in wide-format, with assets as columns,
and index coerced to be tz-aware.
"""
if isinstance(prices, (pd.DataFrame, pd.Series)):
out = prices.pct_change().iloc[1:]
else:
# Assume np.ndarray
out = np.diff(prices, axis=0)
np.divide(out, prices[:-1], out=out)
return out | python | def simple_returns(prices):
if isinstance(prices, (pd.DataFrame, pd.Series)):
out = prices.pct_change().iloc[1:]
else:
# Assume np.ndarray
out = np.diff(prices, axis=0)
np.divide(out, prices[:-1], out=out)
return out | [
"def",
"simple_returns",
"(",
"prices",
")",
":",
"if",
"isinstance",
"(",
"prices",
",",
"(",
"pd",
".",
"DataFrame",
",",
"pd",
".",
"Series",
")",
")",
":",
"out",
"=",
"prices",
".",
"pct_change",
"(",
")",
".",
"iloc",
"[",
"1",
":",
"]",
"e... | Compute simple returns from a timeseries of prices.
Parameters
----------
prices : pd.Series, pd.DataFrame or np.ndarray
Prices of assets in wide-format, with assets as columns,
and indexed by datetimes.
Returns
-------
returns : array-like
Returns of assets in wide-format, with assets as columns,
and index coerced to be tz-aware. | [
"Compute",
"simple",
"returns",
"from",
"a",
"timeseries",
"of",
"prices",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L186-L209 |
238,445 | quantopian/empyrical | empyrical/stats.py | cum_returns | def cum_returns(returns, starting_value=0, out=None):
"""
Compute cumulative returns from simple returns.
Parameters
----------
returns : pd.Series, np.ndarray, or pd.DataFrame
Returns of the strategy as a percentage, noncumulative.
- Time series with decimal returns.
- Example::
2015-07-16 -0.012143
2015-07-17 0.045350
2015-07-20 0.030957
2015-07-21 0.004902
- Also accepts two dimensional data. In this case, each column is
cumulated.
starting_value : float, optional
The starting returns.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
cumulative_returns : array-like
Series of cumulative returns.
"""
if len(returns) < 1:
return returns.copy()
nanmask = np.isnan(returns)
if np.any(nanmask):
returns = returns.copy()
returns[nanmask] = 0
allocated_output = out is None
if allocated_output:
out = np.empty_like(returns)
np.add(returns, 1, out=out)
out.cumprod(axis=0, out=out)
if starting_value == 0:
np.subtract(out, 1, out=out)
else:
np.multiply(out, starting_value, out=out)
if allocated_output:
if returns.ndim == 1 and isinstance(returns, pd.Series):
out = pd.Series(out, index=returns.index)
elif isinstance(returns, pd.DataFrame):
out = pd.DataFrame(
out, index=returns.index, columns=returns.columns,
)
return out | python | def cum_returns(returns, starting_value=0, out=None):
if len(returns) < 1:
return returns.copy()
nanmask = np.isnan(returns)
if np.any(nanmask):
returns = returns.copy()
returns[nanmask] = 0
allocated_output = out is None
if allocated_output:
out = np.empty_like(returns)
np.add(returns, 1, out=out)
out.cumprod(axis=0, out=out)
if starting_value == 0:
np.subtract(out, 1, out=out)
else:
np.multiply(out, starting_value, out=out)
if allocated_output:
if returns.ndim == 1 and isinstance(returns, pd.Series):
out = pd.Series(out, index=returns.index)
elif isinstance(returns, pd.DataFrame):
out = pd.DataFrame(
out, index=returns.index, columns=returns.columns,
)
return out | [
"def",
"cum_returns",
"(",
"returns",
",",
"starting_value",
"=",
"0",
",",
"out",
"=",
"None",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"1",
":",
"return",
"returns",
".",
"copy",
"(",
")",
"nanmask",
"=",
"np",
".",
"isnan",
"(",
"returns... | Compute cumulative returns from simple returns.
Parameters
----------
returns : pd.Series, np.ndarray, or pd.DataFrame
Returns of the strategy as a percentage, noncumulative.
- Time series with decimal returns.
- Example::
2015-07-16 -0.012143
2015-07-17 0.045350
2015-07-20 0.030957
2015-07-21 0.004902
- Also accepts two dimensional data. In this case, each column is
cumulated.
starting_value : float, optional
The starting returns.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
cumulative_returns : array-like
Series of cumulative returns. | [
"Compute",
"cumulative",
"returns",
"from",
"simple",
"returns",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L212-L270 |
238,446 | quantopian/empyrical | empyrical/stats.py | cum_returns_final | def cum_returns_final(returns, starting_value=0):
"""
Compute total returns from simple returns.
Parameters
----------
returns : pd.DataFrame, pd.Series, or np.ndarray
Noncumulative simple returns of one or more timeseries.
starting_value : float, optional
The starting returns.
Returns
-------
total_returns : pd.Series, np.ndarray, or float
If input is 1-dimensional (a Series or 1D numpy array), the result is a
scalar.
If input is 2-dimensional (a DataFrame or 2D numpy array), the result
is a 1D array containing cumulative returns for each column of input.
"""
if len(returns) == 0:
return np.nan
if isinstance(returns, pd.DataFrame):
result = (returns + 1).prod()
else:
result = np.nanprod(returns + 1, axis=0)
if starting_value == 0:
result -= 1
else:
result *= starting_value
return result | python | def cum_returns_final(returns, starting_value=0):
if len(returns) == 0:
return np.nan
if isinstance(returns, pd.DataFrame):
result = (returns + 1).prod()
else:
result = np.nanprod(returns + 1, axis=0)
if starting_value == 0:
result -= 1
else:
result *= starting_value
return result | [
"def",
"cum_returns_final",
"(",
"returns",
",",
"starting_value",
"=",
"0",
")",
":",
"if",
"len",
"(",
"returns",
")",
"==",
"0",
":",
"return",
"np",
".",
"nan",
"if",
"isinstance",
"(",
"returns",
",",
"pd",
".",
"DataFrame",
")",
":",
"result",
... | Compute total returns from simple returns.
Parameters
----------
returns : pd.DataFrame, pd.Series, or np.ndarray
Noncumulative simple returns of one or more timeseries.
starting_value : float, optional
The starting returns.
Returns
-------
total_returns : pd.Series, np.ndarray, or float
If input is 1-dimensional (a Series or 1D numpy array), the result is a
scalar.
If input is 2-dimensional (a DataFrame or 2D numpy array), the result
is a 1D array containing cumulative returns for each column of input. | [
"Compute",
"total",
"returns",
"from",
"simple",
"returns",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L273-L306 |
238,447 | quantopian/empyrical | empyrical/stats.py | aggregate_returns | def aggregate_returns(returns, convert_to):
"""
Aggregates returns by week, month, or year.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
convert_to : str
Can be 'weekly', 'monthly', or 'yearly'.
Returns
-------
aggregated_returns : pd.Series
"""
def cumulate_returns(x):
return cum_returns(x).iloc[-1]
if convert_to == WEEKLY:
grouping = [lambda x: x.year, lambda x: x.isocalendar()[1]]
elif convert_to == MONTHLY:
grouping = [lambda x: x.year, lambda x: x.month]
elif convert_to == YEARLY:
grouping = [lambda x: x.year]
else:
raise ValueError(
'convert_to must be {}, {} or {}'.format(WEEKLY, MONTHLY, YEARLY)
)
return returns.groupby(grouping).apply(cumulate_returns) | python | def aggregate_returns(returns, convert_to):
def cumulate_returns(x):
return cum_returns(x).iloc[-1]
if convert_to == WEEKLY:
grouping = [lambda x: x.year, lambda x: x.isocalendar()[1]]
elif convert_to == MONTHLY:
grouping = [lambda x: x.year, lambda x: x.month]
elif convert_to == YEARLY:
grouping = [lambda x: x.year]
else:
raise ValueError(
'convert_to must be {}, {} or {}'.format(WEEKLY, MONTHLY, YEARLY)
)
return returns.groupby(grouping).apply(cumulate_returns) | [
"def",
"aggregate_returns",
"(",
"returns",
",",
"convert_to",
")",
":",
"def",
"cumulate_returns",
"(",
"x",
")",
":",
"return",
"cum_returns",
"(",
"x",
")",
".",
"iloc",
"[",
"-",
"1",
"]",
"if",
"convert_to",
"==",
"WEEKLY",
":",
"grouping",
"=",
"... | Aggregates returns by week, month, or year.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
convert_to : str
Can be 'weekly', 'monthly', or 'yearly'.
Returns
-------
aggregated_returns : pd.Series | [
"Aggregates",
"returns",
"by",
"week",
"month",
"or",
"year",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L309-L340 |
238,448 | quantopian/empyrical | empyrical/stats.py | max_drawdown | def max_drawdown(returns, out=None):
"""
Determines the maximum drawdown of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
max_drawdown : float
Note
-----
See https://en.wikipedia.org/wiki/Drawdown_(economics) for more details.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 1:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
returns_array = np.asanyarray(returns)
cumulative = np.empty(
(returns.shape[0] + 1,) + returns.shape[1:],
dtype='float64',
)
cumulative[0] = start = 100
cum_returns(returns_array, starting_value=start, out=cumulative[1:])
max_return = np.fmax.accumulate(cumulative, axis=0)
nanmin((cumulative - max_return) / max_return, axis=0, out=out)
if returns_1d:
out = out.item()
elif allocated_output and isinstance(returns, pd.DataFrame):
out = pd.Series(out)
return out | python | def max_drawdown(returns, out=None):
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 1:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
returns_array = np.asanyarray(returns)
cumulative = np.empty(
(returns.shape[0] + 1,) + returns.shape[1:],
dtype='float64',
)
cumulative[0] = start = 100
cum_returns(returns_array, starting_value=start, out=cumulative[1:])
max_return = np.fmax.accumulate(cumulative, axis=0)
nanmin((cumulative - max_return) / max_return, axis=0, out=out)
if returns_1d:
out = out.item()
elif allocated_output and isinstance(returns, pd.DataFrame):
out = pd.Series(out)
return out | [
"def",
"max_drawdown",
"(",
"returns",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",
"=",
"np",
".",
"empty",
"(",
"returns",
".",
"shape",
"[",
"1",
":",
"]",
")",
"returns_1d",
... | Determines the maximum drawdown of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
max_drawdown : float
Note
-----
See https://en.wikipedia.org/wiki/Drawdown_(economics) for more details. | [
"Determines",
"the",
"maximum",
"drawdown",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L343-L393 |
238,449 | quantopian/empyrical | empyrical/stats.py | annual_return | def annual_return(returns, period=DAILY, annualization=None):
"""
Determines the mean annual growth rate of returns. This is equivilent
to the compound annual growth rate.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
annual_return : float
Annual Return as CAGR (Compounded Annual Growth Rate).
"""
if len(returns) < 1:
return np.nan
ann_factor = annualization_factor(period, annualization)
num_years = len(returns) / ann_factor
# Pass array to ensure index -1 looks up successfully.
ending_value = cum_returns_final(returns, starting_value=1)
return ending_value ** (1 / num_years) - 1 | python | def annual_return(returns, period=DAILY, annualization=None):
if len(returns) < 1:
return np.nan
ann_factor = annualization_factor(period, annualization)
num_years = len(returns) / ann_factor
# Pass array to ensure index -1 looks up successfully.
ending_value = cum_returns_final(returns, starting_value=1)
return ending_value ** (1 / num_years) - 1 | [
"def",
"annual_return",
"(",
"returns",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"1",
":",
"return",
"np",
".",
"nan",
"ann_factor",
"=",
"annualization_factor",
"(",
"period",
",",
... | Determines the mean annual growth rate of returns. This is equivilent
to the compound annual growth rate.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
annual_return : float
Annual Return as CAGR (Compounded Annual Growth Rate). | [
"Determines",
"the",
"mean",
"annual",
"growth",
"rate",
"of",
"returns",
".",
"This",
"is",
"equivilent",
"to",
"the",
"compound",
"annual",
"growth",
"rate",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L399-L438 |
238,450 | quantopian/empyrical | empyrical/stats.py | annual_volatility | def annual_volatility(returns,
period=DAILY,
alpha=2.0,
annualization=None,
out=None):
"""
Determines the annual volatility of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
alpha : float, optional
Scaling relation (Levy stability exponent).
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
annual_volatility : float
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
ann_factor = annualization_factor(period, annualization)
nanstd(returns, ddof=1, axis=0, out=out)
out = np.multiply(out, ann_factor ** (1.0 / alpha), out=out)
if returns_1d:
out = out.item()
return out | python | def annual_volatility(returns,
period=DAILY,
alpha=2.0,
annualization=None,
out=None):
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
ann_factor = annualization_factor(period, annualization)
nanstd(returns, ddof=1, axis=0, out=out)
out = np.multiply(out, ann_factor ** (1.0 / alpha), out=out)
if returns_1d:
out = out.item()
return out | [
"def",
"annual_volatility",
"(",
"returns",
",",
"period",
"=",
"DAILY",
",",
"alpha",
"=",
"2.0",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",
"... | Determines the annual volatility of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Periodic returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
alpha : float, optional
Scaling relation (Levy stability exponent).
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
annual_volatility : float | [
"Determines",
"the",
"annual",
"volatility",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L478-L531 |
238,451 | quantopian/empyrical | empyrical/stats.py | calmar_ratio | def calmar_ratio(returns, period=DAILY, annualization=None):
"""
Determines the Calmar ratio, or drawdown ratio, of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
calmar_ratio : float
Calmar ratio (drawdown ratio) as float. Returns np.nan if there is no
calmar ratio.
Note
-----
See https://en.wikipedia.org/wiki/Calmar_ratio for more details.
"""
max_dd = max_drawdown(returns=returns)
if max_dd < 0:
temp = annual_return(
returns=returns,
period=period,
annualization=annualization
) / abs(max_dd)
else:
return np.nan
if np.isinf(temp):
return np.nan
return temp | python | def calmar_ratio(returns, period=DAILY, annualization=None):
max_dd = max_drawdown(returns=returns)
if max_dd < 0:
temp = annual_return(
returns=returns,
period=period,
annualization=annualization
) / abs(max_dd)
else:
return np.nan
if np.isinf(temp):
return np.nan
return temp | [
"def",
"calmar_ratio",
"(",
"returns",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
")",
":",
"max_dd",
"=",
"max_drawdown",
"(",
"returns",
"=",
"returns",
")",
"if",
"max_dd",
"<",
"0",
":",
"temp",
"=",
"annual_return",
"(",
"return... | Determines the Calmar ratio, or drawdown ratio, of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
Returns
-------
calmar_ratio : float
Calmar ratio (drawdown ratio) as float. Returns np.nan if there is no
calmar ratio.
Note
-----
See https://en.wikipedia.org/wiki/Calmar_ratio for more details. | [
"Determines",
"the",
"Calmar",
"ratio",
"or",
"drawdown",
"ratio",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L539-L587 |
238,452 | quantopian/empyrical | empyrical/stats.py | omega_ratio | def omega_ratio(returns, risk_free=0.0, required_return=0.0,
annualization=APPROX_BDAYS_PER_YEAR):
"""Determines the Omega ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period
required_return : float, optional
Minimum acceptance return of the investor. Threshold over which to
consider positive vs negative returns. It will be converted to a
value appropriate for the period of the returns. E.g. An annual minimum
acceptable return of 100 will translate to a minimum acceptable
return of 0.018.
annualization : int, optional
Factor used to convert the required_return into a daily
value. Enter 1 if no time period conversion is necessary.
Returns
-------
omega_ratio : float
Note
-----
See https://en.wikipedia.org/wiki/Omega_ratio for more details.
"""
if len(returns) < 2:
return np.nan
if annualization == 1:
return_threshold = required_return
elif required_return <= -1:
return np.nan
else:
return_threshold = (1 + required_return) ** \
(1. / annualization) - 1
returns_less_thresh = returns - risk_free - return_threshold
numer = sum(returns_less_thresh[returns_less_thresh > 0.0])
denom = -1.0 * sum(returns_less_thresh[returns_less_thresh < 0.0])
if denom > 0.0:
return numer / denom
else:
return np.nan | python | def omega_ratio(returns, risk_free=0.0, required_return=0.0,
annualization=APPROX_BDAYS_PER_YEAR):
if len(returns) < 2:
return np.nan
if annualization == 1:
return_threshold = required_return
elif required_return <= -1:
return np.nan
else:
return_threshold = (1 + required_return) ** \
(1. / annualization) - 1
returns_less_thresh = returns - risk_free - return_threshold
numer = sum(returns_less_thresh[returns_less_thresh > 0.0])
denom = -1.0 * sum(returns_less_thresh[returns_less_thresh < 0.0])
if denom > 0.0:
return numer / denom
else:
return np.nan | [
"def",
"omega_ratio",
"(",
"returns",
",",
"risk_free",
"=",
"0.0",
",",
"required_return",
"=",
"0.0",
",",
"annualization",
"=",
"APPROX_BDAYS_PER_YEAR",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"2",
":",
"return",
"np",
".",
"nan",
"if",
"annu... | Determines the Omega ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period
required_return : float, optional
Minimum acceptance return of the investor. Threshold over which to
consider positive vs negative returns. It will be converted to a
value appropriate for the period of the returns. E.g. An annual minimum
acceptable return of 100 will translate to a minimum acceptable
return of 0.018.
annualization : int, optional
Factor used to convert the required_return into a daily
value. Enter 1 if no time period conversion is necessary.
Returns
-------
omega_ratio : float
Note
-----
See https://en.wikipedia.org/wiki/Omega_ratio for more details. | [
"Determines",
"the",
"Omega",
"ratio",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L590-L640 |
238,453 | quantopian/empyrical | empyrical/stats.py | sharpe_ratio | def sharpe_ratio(returns,
risk_free=0,
period=DAILY,
annualization=None,
out=None):
"""
Determines the Sharpe ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sharpe_ratio : float
nan if insufficient length of returns or if if adjusted returns are 0.
Note
-----
See https://en.wikipedia.org/wiki/Sharpe_ratio for more details.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
return_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if return_1d:
out = out.item()
return out
returns_risk_adj = np.asanyarray(_adjust_returns(returns, risk_free))
ann_factor = annualization_factor(period, annualization)
np.multiply(
np.divide(
nanmean(returns_risk_adj, axis=0),
nanstd(returns_risk_adj, ddof=1, axis=0),
out=out,
),
np.sqrt(ann_factor),
out=out,
)
if return_1d:
out = out.item()
return out | python | def sharpe_ratio(returns,
risk_free=0,
period=DAILY,
annualization=None,
out=None):
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
return_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if return_1d:
out = out.item()
return out
returns_risk_adj = np.asanyarray(_adjust_returns(returns, risk_free))
ann_factor = annualization_factor(period, annualization)
np.multiply(
np.divide(
nanmean(returns_risk_adj, axis=0),
nanstd(returns_risk_adj, ddof=1, axis=0),
out=out,
),
np.sqrt(ann_factor),
out=out,
)
if return_1d:
out = out.item()
return out | [
"def",
"sharpe_ratio",
"(",
"returns",
",",
"risk_free",
"=",
"0",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",
"=",... | Determines the Sharpe ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
risk_free : int, float
Constant risk-free return throughout the period.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sharpe_ratio : float
nan if insufficient length of returns or if if adjusted returns are 0.
Note
-----
See https://en.wikipedia.org/wiki/Sharpe_ratio for more details. | [
"Determines",
"the",
"Sharpe",
"ratio",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L643-L712 |
238,454 | quantopian/empyrical | empyrical/stats.py | sortino_ratio | def sortino_ratio(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None,
_downside_risk=None):
"""
Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
_downside_risk : float, optional
The downside risk of the given inputs, if known. Will be calculated if
not provided.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sortino_ratio : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
return_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if return_1d:
out = out.item()
return out
adj_returns = np.asanyarray(_adjust_returns(returns, required_return))
ann_factor = annualization_factor(period, annualization)
average_annual_return = nanmean(adj_returns, axis=0) * ann_factor
annualized_downside_risk = (
_downside_risk
if _downside_risk is not None else
downside_risk(returns, required_return, period, annualization)
)
np.divide(average_annual_return, annualized_downside_risk, out=out)
if return_1d:
out = out.item()
elif isinstance(returns, pd.DataFrame):
out = pd.Series(out)
return out | python | def sortino_ratio(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None,
_downside_risk=None):
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
return_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if return_1d:
out = out.item()
return out
adj_returns = np.asanyarray(_adjust_returns(returns, required_return))
ann_factor = annualization_factor(period, annualization)
average_annual_return = nanmean(adj_returns, axis=0) * ann_factor
annualized_downside_risk = (
_downside_risk
if _downside_risk is not None else
downside_risk(returns, required_return, period, annualization)
)
np.divide(average_annual_return, annualized_downside_risk, out=out)
if return_1d:
out = out.item()
elif isinstance(returns, pd.DataFrame):
out = pd.Series(out)
return out | [
"def",
"sortino_ratio",
"(",
"returns",
",",
"required_return",
"=",
"0",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
",",
"_downside_risk",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
... | Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
_downside_risk : float, optional
The downside risk of the given inputs, if known. Will be calculated if
not provided.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sortino_ratio : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details. | [
"Determines",
"the",
"Sortino",
"ratio",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L718-L796 |
238,455 | quantopian/empyrical | empyrical/stats.py | downside_risk | def downside_risk(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None):
"""
Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
downside_deviation : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details, specifically why using the
standard deviation of the negative returns is not correct.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 1:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
ann_factor = annualization_factor(period, annualization)
downside_diff = np.clip(
_adjust_returns(
np.asanyarray(returns),
np.asanyarray(required_return),
),
np.NINF,
0,
)
np.square(downside_diff, out=downside_diff)
nanmean(downside_diff, axis=0, out=out)
np.sqrt(out, out=out)
np.multiply(out, np.sqrt(ann_factor), out=out)
if returns_1d:
out = out.item()
elif isinstance(returns, pd.DataFrame):
out = pd.Series(out, index=returns.columns)
return out | python | def downside_risk(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None):
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 1:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
ann_factor = annualization_factor(period, annualization)
downside_diff = np.clip(
_adjust_returns(
np.asanyarray(returns),
np.asanyarray(required_return),
),
np.NINF,
0,
)
np.square(downside_diff, out=downside_diff)
nanmean(downside_diff, axis=0, out=out)
np.sqrt(out, out=out)
np.multiply(out, np.sqrt(ann_factor), out=out)
if returns_1d:
out = out.item()
elif isinstance(returns, pd.DataFrame):
out = pd.Series(out, index=returns.columns)
return out | [
"def",
"downside_risk",
"(",
"returns",
",",
"required_return",
"=",
"0",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",... | Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
downside_deviation : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details, specifically why using the
standard deviation of the negative returns is not correct. | [
"Determines",
"the",
"downside",
"deviation",
"below",
"a",
"threshold"
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L802-L879 |
238,456 | quantopian/empyrical | empyrical/stats.py | excess_sharpe | def excess_sharpe(returns, factor_returns, out=None):
"""
Determines the Excess Sharpe of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns: float / series
Benchmark return to compare returns against.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
excess_sharpe : float
Note
-----
The excess Sharpe is a simplified Information Ratio that uses
tracking error rather than "active risk" as the denominator.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
active_return = _adjust_returns(returns, factor_returns)
tracking_error = np.nan_to_num(nanstd(active_return, ddof=1, axis=0))
out = np.divide(
nanmean(active_return, axis=0, out=out),
tracking_error,
out=out,
)
if returns_1d:
out = out.item()
return out | python | def excess_sharpe(returns, factor_returns, out=None):
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
active_return = _adjust_returns(returns, factor_returns)
tracking_error = np.nan_to_num(nanstd(active_return, ddof=1, axis=0))
out = np.divide(
nanmean(active_return, axis=0, out=out),
tracking_error,
out=out,
)
if returns_1d:
out = out.item()
return out | [
"def",
"excess_sharpe",
"(",
"returns",
",",
"factor_returns",
",",
"out",
"=",
"None",
")",
":",
"allocated_output",
"=",
"out",
"is",
"None",
"if",
"allocated_output",
":",
"out",
"=",
"np",
".",
"empty",
"(",
"returns",
".",
"shape",
"[",
"1",
":",
... | Determines the Excess Sharpe of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns: float / series
Benchmark return to compare returns against.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
excess_sharpe : float
Note
-----
The excess Sharpe is a simplified Information Ratio that uses
tracking error rather than "active risk" as the denominator. | [
"Determines",
"the",
"Excess",
"Sharpe",
"of",
"a",
"strategy",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L885-L931 |
238,457 | quantopian/empyrical | empyrical/stats.py | _to_pandas | def _to_pandas(ob):
"""Convert an array-like to a pandas object.
Parameters
----------
ob : array-like
The object to convert.
Returns
-------
pandas_structure : pd.Series or pd.DataFrame
The correct structure based on the dimensionality of the data.
"""
if isinstance(ob, (pd.Series, pd.DataFrame)):
return ob
if ob.ndim == 1:
return pd.Series(ob)
elif ob.ndim == 2:
return pd.DataFrame(ob)
else:
raise ValueError(
'cannot convert array of dim > 2 to a pandas structure',
) | python | def _to_pandas(ob):
if isinstance(ob, (pd.Series, pd.DataFrame)):
return ob
if ob.ndim == 1:
return pd.Series(ob)
elif ob.ndim == 2:
return pd.DataFrame(ob)
else:
raise ValueError(
'cannot convert array of dim > 2 to a pandas structure',
) | [
"def",
"_to_pandas",
"(",
"ob",
")",
":",
"if",
"isinstance",
"(",
"ob",
",",
"(",
"pd",
".",
"Series",
",",
"pd",
".",
"DataFrame",
")",
")",
":",
"return",
"ob",
"if",
"ob",
".",
"ndim",
"==",
"1",
":",
"return",
"pd",
".",
"Series",
"(",
"ob... | Convert an array-like to a pandas object.
Parameters
----------
ob : array-like
The object to convert.
Returns
-------
pandas_structure : pd.Series or pd.DataFrame
The correct structure based on the dimensionality of the data. | [
"Convert",
"an",
"array",
"-",
"like",
"to",
"a",
"pandas",
"object",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L937-L960 |
238,458 | quantopian/empyrical | empyrical/stats.py | _aligned_series | def _aligned_series(*many_series):
"""
Return a new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
Parameters
----------
*many_series
The series to align.
Returns
-------
aligned_series : iterable[array-like]
A new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
"""
head = many_series[0]
tail = many_series[1:]
n = len(head)
if (isinstance(head, np.ndarray) and
all(len(s) == n and isinstance(s, np.ndarray) for s in tail)):
# optimization: ndarrays of the same length are already aligned
return many_series
# dataframe has no ``itervalues``
return (
v
for _, v in iteritems(pd.concat(map(_to_pandas, many_series), axis=1))
) | python | def _aligned_series(*many_series):
head = many_series[0]
tail = many_series[1:]
n = len(head)
if (isinstance(head, np.ndarray) and
all(len(s) == n and isinstance(s, np.ndarray) for s in tail)):
# optimization: ndarrays of the same length are already aligned
return many_series
# dataframe has no ``itervalues``
return (
v
for _, v in iteritems(pd.concat(map(_to_pandas, many_series), axis=1))
) | [
"def",
"_aligned_series",
"(",
"*",
"many_series",
")",
":",
"head",
"=",
"many_series",
"[",
"0",
"]",
"tail",
"=",
"many_series",
"[",
"1",
":",
"]",
"n",
"=",
"len",
"(",
"head",
")",
"if",
"(",
"isinstance",
"(",
"head",
",",
"np",
".",
"ndarra... | Return a new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
Parameters
----------
*many_series
The series to align.
Returns
-------
aligned_series : iterable[array-like]
A new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values. | [
"Return",
"a",
"new",
"list",
"of",
"series",
"containing",
"the",
"data",
"in",
"the",
"input",
"series",
"but",
"with",
"their",
"indices",
"aligned",
".",
"NaNs",
"will",
"be",
"filled",
"in",
"for",
"missing",
"values",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L963-L992 |
238,459 | quantopian/empyrical | empyrical/stats.py | roll_alpha_beta | def roll_alpha_beta(returns, factor_returns, window=10, **kwargs):
"""
Computes alpha and beta over a rolling window.
Parameters
----------
lhs : array-like
The first array to pass to the rolling alpha-beta.
rhs : array-like
The second array to pass to the rolling alpha-beta.
window : int
Size of the rolling window in terms of the periodicity of the data.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
**kwargs
Forwarded to :func:`~empyrical.alpha_beta`.
"""
returns, factor_returns = _aligned_series(returns, factor_returns)
return roll_alpha_beta_aligned(
returns,
factor_returns,
window=window,
**kwargs
) | python | def roll_alpha_beta(returns, factor_returns, window=10, **kwargs):
returns, factor_returns = _aligned_series(returns, factor_returns)
return roll_alpha_beta_aligned(
returns,
factor_returns,
window=window,
**kwargs
) | [
"def",
"roll_alpha_beta",
"(",
"returns",
",",
"factor_returns",
",",
"window",
"=",
"10",
",",
"*",
"*",
"kwargs",
")",
":",
"returns",
",",
"factor_returns",
"=",
"_aligned_series",
"(",
"returns",
",",
"factor_returns",
")",
"return",
"roll_alpha_beta_aligned... | Computes alpha and beta over a rolling window.
Parameters
----------
lhs : array-like
The first array to pass to the rolling alpha-beta.
rhs : array-like
The second array to pass to the rolling alpha-beta.
window : int
Size of the rolling window in terms of the periodicity of the data.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
**kwargs
Forwarded to :func:`~empyrical.alpha_beta`. | [
"Computes",
"alpha",
"and",
"beta",
"over",
"a",
"rolling",
"window",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1049-L1074 |
238,460 | quantopian/empyrical | empyrical/stats.py | stability_of_timeseries | def stability_of_timeseries(returns):
"""Determines R-squared of a linear fit to the cumulative
log returns. Computes an ordinary least squares linear fit,
and returns R-squared.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
Returns
-------
float
R-squared.
"""
if len(returns) < 2:
return np.nan
returns = np.asanyarray(returns)
returns = returns[~np.isnan(returns)]
cum_log_returns = np.log1p(returns).cumsum()
rhat = stats.linregress(np.arange(len(cum_log_returns)),
cum_log_returns)[2]
return rhat ** 2 | python | def stability_of_timeseries(returns):
if len(returns) < 2:
return np.nan
returns = np.asanyarray(returns)
returns = returns[~np.isnan(returns)]
cum_log_returns = np.log1p(returns).cumsum()
rhat = stats.linregress(np.arange(len(cum_log_returns)),
cum_log_returns)[2]
return rhat ** 2 | [
"def",
"stability_of_timeseries",
"(",
"returns",
")",
":",
"if",
"len",
"(",
"returns",
")",
"<",
"2",
":",
"return",
"np",
".",
"nan",
"returns",
"=",
"np",
".",
"asanyarray",
"(",
"returns",
")",
"returns",
"=",
"returns",
"[",
"~",
"np",
".",
"is... | Determines R-squared of a linear fit to the cumulative
log returns. Computes an ordinary least squares linear fit,
and returns R-squared.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
Returns
-------
float
R-squared. | [
"Determines",
"R",
"-",
"squared",
"of",
"a",
"linear",
"fit",
"to",
"the",
"cumulative",
"log",
"returns",
".",
"Computes",
"an",
"ordinary",
"least",
"squares",
"linear",
"fit",
"and",
"returns",
"R",
"-",
"squared",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1454-L1481 |
238,461 | quantopian/empyrical | empyrical/stats.py | capture | def capture(returns, factor_returns, period=DAILY):
"""
Compute capture ratio.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
capture_ratio : float
Note
----
See http://www.investopedia.com/terms/u/up-market-capture-ratio.asp for
details.
"""
return (annual_return(returns, period=period) /
annual_return(factor_returns, period=period)) | python | def capture(returns, factor_returns, period=DAILY):
return (annual_return(returns, period=period) /
annual_return(factor_returns, period=period)) | [
"def",
"capture",
"(",
"returns",
",",
"factor_returns",
",",
"period",
"=",
"DAILY",
")",
":",
"return",
"(",
"annual_return",
"(",
"returns",
",",
"period",
"=",
"period",
")",
"/",
"annual_return",
"(",
"factor_returns",
",",
"period",
"=",
"period",
")... | Compute capture ratio.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
capture_ratio : float
Note
----
See http://www.investopedia.com/terms/u/up-market-capture-ratio.asp for
details. | [
"Compute",
"capture",
"ratio",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1514-L1546 |
238,462 | quantopian/empyrical | empyrical/stats.py | up_capture | def up_capture(returns, factor_returns, **kwargs):
"""
Compute the capture ratio for periods when the benchmark return is positive
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
up_capture : float
Note
----
See http://www.investopedia.com/terms/u/up-market-capture-ratio.asp for
more information.
"""
return up(returns, factor_returns, function=capture, **kwargs) | python | def up_capture(returns, factor_returns, **kwargs):
return up(returns, factor_returns, function=capture, **kwargs) | [
"def",
"up_capture",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"up",
"(",
"returns",
",",
"factor_returns",
",",
"function",
"=",
"capture",
",",
"*",
"*",
"kwargs",
")"
] | Compute the capture ratio for periods when the benchmark return is positive
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
up_capture : float
Note
----
See http://www.investopedia.com/terms/u/up-market-capture-ratio.asp for
more information. | [
"Compute",
"the",
"capture",
"ratio",
"for",
"periods",
"when",
"the",
"benchmark",
"return",
"is",
"positive"
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1549-L1580 |
238,463 | quantopian/empyrical | empyrical/stats.py | down_capture | def down_capture(returns, factor_returns, **kwargs):
"""
Compute the capture ratio for periods when the benchmark return is negative
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
down_capture : float
Note
----
See http://www.investopedia.com/terms/d/down-market-capture-ratio.asp for
more information.
"""
return down(returns, factor_returns, function=capture, **kwargs) | python | def down_capture(returns, factor_returns, **kwargs):
return down(returns, factor_returns, function=capture, **kwargs) | [
"def",
"down_capture",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"down",
"(",
"returns",
",",
"factor_returns",
",",
"function",
"=",
"capture",
",",
"*",
"*",
"kwargs",
")"
] | Compute the capture ratio for periods when the benchmark return is negative
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
down_capture : float
Note
----
See http://www.investopedia.com/terms/d/down-market-capture-ratio.asp for
more information. | [
"Compute",
"the",
"capture",
"ratio",
"for",
"periods",
"when",
"the",
"benchmark",
"return",
"is",
"negative"
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1583-L1614 |
238,464 | quantopian/empyrical | empyrical/stats.py | up_down_capture | def up_down_capture(returns, factor_returns, **kwargs):
"""
Computes the ratio of up_capture to down_capture.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
up_down_capture : float
the updown capture ratio
"""
return (up_capture(returns, factor_returns, **kwargs) /
down_capture(returns, factor_returns, **kwargs)) | python | def up_down_capture(returns, factor_returns, **kwargs):
return (up_capture(returns, factor_returns, **kwargs) /
down_capture(returns, factor_returns, **kwargs)) | [
"def",
"up_down_capture",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"(",
"up_capture",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
"/",
"down_capture",
"(",
"returns",
",",
"factor_returns",
... | Computes the ratio of up_capture to down_capture.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
Noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
Returns
-------
up_down_capture : float
the updown capture ratio | [
"Computes",
"the",
"ratio",
"of",
"up_capture",
"to",
"down_capture",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1617-L1645 |
238,465 | quantopian/empyrical | empyrical/stats.py | up_alpha_beta | def up_alpha_beta(returns, factor_returns, **kwargs):
"""
Computes alpha and beta for periods when the benchmark return is positive.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
float
Alpha.
float
Beta.
"""
return up(returns, factor_returns, function=alpha_beta_aligned, **kwargs) | python | def up_alpha_beta(returns, factor_returns, **kwargs):
return up(returns, factor_returns, function=alpha_beta_aligned, **kwargs) | [
"def",
"up_alpha_beta",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"up",
"(",
"returns",
",",
"factor_returns",
",",
"function",
"=",
"alpha_beta_aligned",
",",
"*",
"*",
"kwargs",
")"
] | Computes alpha and beta for periods when the benchmark return is positive.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
float
Alpha.
float
Beta. | [
"Computes",
"alpha",
"and",
"beta",
"for",
"periods",
"when",
"the",
"benchmark",
"return",
"is",
"positive",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1648-L1663 |
238,466 | quantopian/empyrical | empyrical/stats.py | down_alpha_beta | def down_alpha_beta(returns, factor_returns, **kwargs):
"""
Computes alpha and beta for periods when the benchmark return is negative.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
alpha : float
beta : float
"""
return down(returns, factor_returns, function=alpha_beta_aligned, **kwargs) | python | def down_alpha_beta(returns, factor_returns, **kwargs):
return down(returns, factor_returns, function=alpha_beta_aligned, **kwargs) | [
"def",
"down_alpha_beta",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"down",
"(",
"returns",
",",
"factor_returns",
",",
"function",
"=",
"alpha_beta_aligned",
",",
"*",
"*",
"kwargs",
")"
] | Computes alpha and beta for periods when the benchmark return is negative.
Parameters
----------
see documentation for `alpha_beta`.
Returns
-------
alpha : float
beta : float | [
"Computes",
"alpha",
"and",
"beta",
"for",
"periods",
"when",
"the",
"benchmark",
"return",
"is",
"negative",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L1666-L1679 |
238,467 | quantopian/empyrical | empyrical/utils.py | roll | def roll(*args, **kwargs):
"""
Calculates a given statistic across a rolling time period.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
Benchmark return to compare returns against.
function:
the function to run for each rolling window.
window (keyword): int
the number of periods included in each calculation.
(other keywords): other keywords that are required to be passed to the
function in the 'function' argument may also be passed in.
Returns
-------
np.ndarray, pd.Series
depends on input type
ndarray(s) ==> ndarray
Series(s) ==> pd.Series
A Series or ndarray of the results of the stat across the rolling
window.
"""
func = kwargs.pop('function')
window = kwargs.pop('window')
if len(args) > 2:
raise ValueError("Cannot pass more than 2 return sets")
if len(args) == 2:
if not isinstance(args[0], type(args[1])):
raise ValueError("The two returns arguments are not the same.")
if isinstance(args[0], np.ndarray):
return _roll_ndarray(func, window, *args, **kwargs)
return _roll_pandas(func, window, *args, **kwargs) | python | def roll(*args, **kwargs):
func = kwargs.pop('function')
window = kwargs.pop('window')
if len(args) > 2:
raise ValueError("Cannot pass more than 2 return sets")
if len(args) == 2:
if not isinstance(args[0], type(args[1])):
raise ValueError("The two returns arguments are not the same.")
if isinstance(args[0], np.ndarray):
return _roll_ndarray(func, window, *args, **kwargs)
return _roll_pandas(func, window, *args, **kwargs) | [
"def",
"roll",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"kwargs",
".",
"pop",
"(",
"'function'",
")",
"window",
"=",
"kwargs",
".",
"pop",
"(",
"'window'",
")",
"if",
"len",
"(",
"args",
")",
">",
"2",
":",
"raise",
"Va... | Calculates a given statistic across a rolling time period.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
Benchmark return to compare returns against.
function:
the function to run for each rolling window.
window (keyword): int
the number of periods included in each calculation.
(other keywords): other keywords that are required to be passed to the
function in the 'function' argument may also be passed in.
Returns
-------
np.ndarray, pd.Series
depends on input type
ndarray(s) ==> ndarray
Series(s) ==> pd.Series
A Series or ndarray of the results of the stat across the rolling
window. | [
"Calculates",
"a",
"given",
"statistic",
"across",
"a",
"rolling",
"time",
"period",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L78-L118 |
238,468 | quantopian/empyrical | empyrical/utils.py | up | def up(returns, factor_returns, **kwargs):
"""
Calculates a given statistic filtering only positive factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
Benchmark return to compare returns against.
function:
the function to run for each rolling window.
(other keywords): other keywords that are required to be passed to the
function in the 'function' argument may also be passed in.
Returns
-------
Same as the return of the function
"""
func = kwargs.pop('function')
returns = returns[factor_returns > 0]
factor_returns = factor_returns[factor_returns > 0]
return func(returns, factor_returns, **kwargs) | python | def up(returns, factor_returns, **kwargs):
func = kwargs.pop('function')
returns = returns[factor_returns > 0]
factor_returns = factor_returns[factor_returns > 0]
return func(returns, factor_returns, **kwargs) | [
"def",
"up",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"kwargs",
".",
"pop",
"(",
"'function'",
")",
"returns",
"=",
"returns",
"[",
"factor_returns",
">",
"0",
"]",
"factor_returns",
"=",
"factor_returns",
"[... | Calculates a given statistic filtering only positive factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
Benchmark return to compare returns against.
function:
the function to run for each rolling window.
(other keywords): other keywords that are required to be passed to the
function in the 'function' argument may also be passed in.
Returns
-------
Same as the return of the function | [
"Calculates",
"a",
"given",
"statistic",
"filtering",
"only",
"positive",
"factor",
"return",
"periods",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L121-L144 |
238,469 | quantopian/empyrical | empyrical/utils.py | down | def down(returns, factor_returns, **kwargs):
"""
Calculates a given statistic filtering only negative factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
Benchmark return to compare returns against.
function:
the function to run for each rolling window.
(other keywords): other keywords that are required to be passed to the
function in the 'function' argument may also be passed in.
Returns
-------
Same as the return of the 'function'
"""
func = kwargs.pop('function')
returns = returns[factor_returns < 0]
factor_returns = factor_returns[factor_returns < 0]
return func(returns, factor_returns, **kwargs) | python | def down(returns, factor_returns, **kwargs):
func = kwargs.pop('function')
returns = returns[factor_returns < 0]
factor_returns = factor_returns[factor_returns < 0]
return func(returns, factor_returns, **kwargs) | [
"def",
"down",
"(",
"returns",
",",
"factor_returns",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"kwargs",
".",
"pop",
"(",
"'function'",
")",
"returns",
"=",
"returns",
"[",
"factor_returns",
"<",
"0",
"]",
"factor_returns",
"=",
"factor_returns",
... | Calculates a given statistic filtering only negative factor return periods.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optional): float / series
Benchmark return to compare returns against.
function:
the function to run for each rolling window.
(other keywords): other keywords that are required to be passed to the
function in the 'function' argument may also be passed in.
Returns
-------
Same as the return of the 'function' | [
"Calculates",
"a",
"given",
"statistic",
"filtering",
"only",
"negative",
"factor",
"return",
"periods",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L147-L170 |
238,470 | quantopian/empyrical | empyrical/utils.py | get_treasury_yield | def get_treasury_yield(start=None, end=None, period='3MO'):
"""
Load treasury yields from FRED.
Parameters
----------
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
Defaults to latest date available.
period : {'1MO', '3MO', '6MO', 1', '5', '10'}, optional
Which maturity to use.
Returns
-------
pd.Series
Annual treasury yield for every day.
"""
if start is None:
start = '1/1/1970'
if end is None:
end = _1_bday_ago()
treasury = web.DataReader("DGS3{}".format(period), "fred",
start, end)
treasury = treasury.ffill()
return treasury | python | def get_treasury_yield(start=None, end=None, period='3MO'):
if start is None:
start = '1/1/1970'
if end is None:
end = _1_bday_ago()
treasury = web.DataReader("DGS3{}".format(period), "fred",
start, end)
treasury = treasury.ffill()
return treasury | [
"def",
"get_treasury_yield",
"(",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"period",
"=",
"'3MO'",
")",
":",
"if",
"start",
"is",
"None",
":",
"start",
"=",
"'1/1/1970'",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"_1_bday_ago",
"(",
")",... | Load treasury yields from FRED.
Parameters
----------
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
Defaults to latest date available.
period : {'1MO', '3MO', '6MO', 1', '5', '10'}, optional
Which maturity to use.
Returns
-------
pd.Series
Annual treasury yield for every day. | [
"Load",
"treasury",
"yields",
"from",
"FRED",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L379-L409 |
238,471 | quantopian/empyrical | empyrical/utils.py | default_returns_func | def default_returns_func(symbol, start=None, end=None):
"""
Gets returns for a symbol.
Queries Yahoo Finance. Attempts to cache SPY.
Parameters
----------
symbol : str
Ticker symbol, e.g. APPL.
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
Defaults to latest date available.
Returns
-------
pd.Series
Daily returns for the symbol.
- See full explanation in tears.create_full_tear_sheet (returns).
"""
if start is None:
start = '1/1/1970'
if end is None:
end = _1_bday_ago()
start = get_utc_timestamp(start)
end = get_utc_timestamp(end)
if symbol == 'SPY':
filepath = data_path('spy.csv')
rets = get_returns_cached(filepath,
get_symbol_returns_from_yahoo,
end,
symbol='SPY',
start='1/1/1970',
end=datetime.now())
rets = rets[start:end]
else:
rets = get_symbol_returns_from_yahoo(symbol, start=start, end=end)
return rets[symbol] | python | def default_returns_func(symbol, start=None, end=None):
if start is None:
start = '1/1/1970'
if end is None:
end = _1_bday_ago()
start = get_utc_timestamp(start)
end = get_utc_timestamp(end)
if symbol == 'SPY':
filepath = data_path('spy.csv')
rets = get_returns_cached(filepath,
get_symbol_returns_from_yahoo,
end,
symbol='SPY',
start='1/1/1970',
end=datetime.now())
rets = rets[start:end]
else:
rets = get_symbol_returns_from_yahoo(symbol, start=start, end=end)
return rets[symbol] | [
"def",
"default_returns_func",
"(",
"symbol",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"if",
"start",
"is",
"None",
":",
"start",
"=",
"'1/1/1970'",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"_1_bday_ago",
"(",
")",
"start",
"=... | Gets returns for a symbol.
Queries Yahoo Finance. Attempts to cache SPY.
Parameters
----------
symbol : str
Ticker symbol, e.g. APPL.
start : date, optional
Earliest date to fetch data for.
Defaults to earliest date available.
end : date, optional
Latest date to fetch data for.
Defaults to latest date available.
Returns
-------
pd.Series
Daily returns for the symbol.
- See full explanation in tears.create_full_tear_sheet (returns). | [
"Gets",
"returns",
"for",
"a",
"symbol",
".",
"Queries",
"Yahoo",
"Finance",
".",
"Attempts",
"to",
"cache",
"SPY",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/utils.py#L452-L495 |
238,472 | quantopian/empyrical | empyrical/perf_attrib.py | perf_attrib | def perf_attrib(returns,
positions,
factor_returns,
factor_loadings):
"""
Attributes the performance of a returns stream to a set of risk factors.
Performance attribution determines how much each risk factor, e.g.,
momentum, the technology sector, etc., contributed to total returns, as
well as the daily exposure to each of the risk factors. The returns that
can be attributed to one of the given risk factors are the
`common_returns`, and the returns that _cannot_ be attributed to a risk
factor are the `specific_returns`. The `common_returns` and
`specific_returns` summed together will always equal the total returns.
Parameters
----------
returns : pd.Series
Returns for each day in the date range.
- Example:
2017-01-01 -0.017098
2017-01-02 0.002683
2017-01-03 -0.008669
positions: pd.Series
Daily holdings in percentages, indexed by date.
- Examples:
dt ticker
2017-01-01 AAPL 0.417582
TLT 0.010989
XOM 0.571429
2017-01-02 AAPL 0.202381
TLT 0.535714
XOM 0.261905
factor_returns : pd.DataFrame
Returns by factor, with date as index and factors as columns
- Example:
momentum reversal
2017-01-01 0.002779 -0.005453
2017-01-02 0.001096 0.010290
factor_loadings : pd.DataFrame
Factor loadings for all days in the date range, with date and ticker as
index, and factors as columns.
- Example:
momentum reversal
dt ticker
2017-01-01 AAPL -1.592914 0.852830
TLT 0.184864 0.895534
XOM 0.993160 1.149353
2017-01-02 AAPL -0.140009 -0.524952
TLT -1.066978 0.185435
XOM -1.798401 0.761549
Returns
-------
tuple of (risk_exposures_portfolio, perf_attribution)
risk_exposures_portfolio : pd.DataFrame
df indexed by datetime, with factors as columns
- Example:
momentum reversal
dt
2017-01-01 -0.238655 0.077123
2017-01-02 0.821872 1.520515
perf_attribution : pd.DataFrame
df with factors, common returns, and specific returns as columns,
and datetimes as index
- Example:
momentum reversal common_returns specific_returns
dt
2017-01-01 0.249087 0.935925 1.185012 1.185012
2017-01-02 -0.003194 -0.400786 -0.403980 -0.403980
Note
----
See https://en.wikipedia.org/wiki/Performance_attribution for more details.
"""
risk_exposures_portfolio = compute_exposures(positions,
factor_loadings)
perf_attrib_by_factor = risk_exposures_portfolio.multiply(factor_returns)
common_returns = perf_attrib_by_factor.sum(axis='columns')
specific_returns = returns - common_returns
returns_df = pd.DataFrame({'total_returns': returns,
'common_returns': common_returns,
'specific_returns': specific_returns})
return (risk_exposures_portfolio,
pd.concat([perf_attrib_by_factor, returns_df], axis='columns')) | python | def perf_attrib(returns,
positions,
factor_returns,
factor_loadings):
risk_exposures_portfolio = compute_exposures(positions,
factor_loadings)
perf_attrib_by_factor = risk_exposures_portfolio.multiply(factor_returns)
common_returns = perf_attrib_by_factor.sum(axis='columns')
specific_returns = returns - common_returns
returns_df = pd.DataFrame({'total_returns': returns,
'common_returns': common_returns,
'specific_returns': specific_returns})
return (risk_exposures_portfolio,
pd.concat([perf_attrib_by_factor, returns_df], axis='columns')) | [
"def",
"perf_attrib",
"(",
"returns",
",",
"positions",
",",
"factor_returns",
",",
"factor_loadings",
")",
":",
"risk_exposures_portfolio",
"=",
"compute_exposures",
"(",
"positions",
",",
"factor_loadings",
")",
"perf_attrib_by_factor",
"=",
"risk_exposures_portfolio",
... | Attributes the performance of a returns stream to a set of risk factors.
Performance attribution determines how much each risk factor, e.g.,
momentum, the technology sector, etc., contributed to total returns, as
well as the daily exposure to each of the risk factors. The returns that
can be attributed to one of the given risk factors are the
`common_returns`, and the returns that _cannot_ be attributed to a risk
factor are the `specific_returns`. The `common_returns` and
`specific_returns` summed together will always equal the total returns.
Parameters
----------
returns : pd.Series
Returns for each day in the date range.
- Example:
2017-01-01 -0.017098
2017-01-02 0.002683
2017-01-03 -0.008669
positions: pd.Series
Daily holdings in percentages, indexed by date.
- Examples:
dt ticker
2017-01-01 AAPL 0.417582
TLT 0.010989
XOM 0.571429
2017-01-02 AAPL 0.202381
TLT 0.535714
XOM 0.261905
factor_returns : pd.DataFrame
Returns by factor, with date as index and factors as columns
- Example:
momentum reversal
2017-01-01 0.002779 -0.005453
2017-01-02 0.001096 0.010290
factor_loadings : pd.DataFrame
Factor loadings for all days in the date range, with date and ticker as
index, and factors as columns.
- Example:
momentum reversal
dt ticker
2017-01-01 AAPL -1.592914 0.852830
TLT 0.184864 0.895534
XOM 0.993160 1.149353
2017-01-02 AAPL -0.140009 -0.524952
TLT -1.066978 0.185435
XOM -1.798401 0.761549
Returns
-------
tuple of (risk_exposures_portfolio, perf_attribution)
risk_exposures_portfolio : pd.DataFrame
df indexed by datetime, with factors as columns
- Example:
momentum reversal
dt
2017-01-01 -0.238655 0.077123
2017-01-02 0.821872 1.520515
perf_attribution : pd.DataFrame
df with factors, common returns, and specific returns as columns,
and datetimes as index
- Example:
momentum reversal common_returns specific_returns
dt
2017-01-01 0.249087 0.935925 1.185012 1.185012
2017-01-02 -0.003194 -0.400786 -0.403980 -0.403980
Note
----
See https://en.wikipedia.org/wiki/Performance_attribution for more details. | [
"Attributes",
"the",
"performance",
"of",
"a",
"returns",
"stream",
"to",
"a",
"set",
"of",
"risk",
"factors",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/perf_attrib.py#L4-L97 |
238,473 | quantopian/empyrical | empyrical/perf_attrib.py | compute_exposures | def compute_exposures(positions, factor_loadings):
"""
Compute daily risk factor exposures.
Parameters
----------
positions: pd.Series
A series of holdings as percentages indexed by date and ticker.
- Examples:
dt ticker
2017-01-01 AAPL 0.417582
TLT 0.010989
XOM 0.571429
2017-01-02 AAPL 0.202381
TLT 0.535714
XOM 0.261905
factor_loadings : pd.DataFrame
Factor loadings for all days in the date range, with date and ticker as
index, and factors as columns.
- Example:
momentum reversal
dt ticker
2017-01-01 AAPL -1.592914 0.852830
TLT 0.184864 0.895534
XOM 0.993160 1.149353
2017-01-02 AAPL -0.140009 -0.524952
TLT -1.066978 0.185435
XOM -1.798401 0.761549
Returns
-------
risk_exposures_portfolio : pd.DataFrame
df indexed by datetime, with factors as columns
- Example:
momentum reversal
dt
2017-01-01 -0.238655 0.077123
2017-01-02 0.821872 1.520515
"""
risk_exposures = factor_loadings.multiply(positions, axis='rows')
return risk_exposures.groupby(level='dt').sum() | python | def compute_exposures(positions, factor_loadings):
risk_exposures = factor_loadings.multiply(positions, axis='rows')
return risk_exposures.groupby(level='dt').sum() | [
"def",
"compute_exposures",
"(",
"positions",
",",
"factor_loadings",
")",
":",
"risk_exposures",
"=",
"factor_loadings",
".",
"multiply",
"(",
"positions",
",",
"axis",
"=",
"'rows'",
")",
"return",
"risk_exposures",
".",
"groupby",
"(",
"level",
"=",
"'dt'",
... | Compute daily risk factor exposures.
Parameters
----------
positions: pd.Series
A series of holdings as percentages indexed by date and ticker.
- Examples:
dt ticker
2017-01-01 AAPL 0.417582
TLT 0.010989
XOM 0.571429
2017-01-02 AAPL 0.202381
TLT 0.535714
XOM 0.261905
factor_loadings : pd.DataFrame
Factor loadings for all days in the date range, with date and ticker as
index, and factors as columns.
- Example:
momentum reversal
dt ticker
2017-01-01 AAPL -1.592914 0.852830
TLT 0.184864 0.895534
XOM 0.993160 1.149353
2017-01-02 AAPL -0.140009 -0.524952
TLT -1.066978 0.185435
XOM -1.798401 0.761549
Returns
-------
risk_exposures_portfolio : pd.DataFrame
df indexed by datetime, with factors as columns
- Example:
momentum reversal
dt
2017-01-01 -0.238655 0.077123
2017-01-02 0.821872 1.520515 | [
"Compute",
"daily",
"risk",
"factor",
"exposures",
"."
] | badbdca75f5b293f28b5e947974894de041d6868 | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/perf_attrib.py#L100-L141 |
238,474 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.has_pending | def has_pending(self):
"""Return True if there are pending test items.
This indicates that collection has finished and nodes are still
processing test items, so this can be thought of as
"the scheduler is active".
"""
if self.workqueue:
return True
for assigned_unit in self.assigned_work.values():
if self._pending_of(assigned_unit) > 0:
return True
return False | python | def has_pending(self):
if self.workqueue:
return True
for assigned_unit in self.assigned_work.values():
if self._pending_of(assigned_unit) > 0:
return True
return False | [
"def",
"has_pending",
"(",
"self",
")",
":",
"if",
"self",
".",
"workqueue",
":",
"return",
"True",
"for",
"assigned_unit",
"in",
"self",
".",
"assigned_work",
".",
"values",
"(",
")",
":",
"if",
"self",
".",
"_pending_of",
"(",
"assigned_unit",
")",
">"... | Return True if there are pending test items.
This indicates that collection has finished and nodes are still
processing test items, so this can be thought of as
"the scheduler is active". | [
"Return",
"True",
"if",
"there",
"are",
"pending",
"test",
"items",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L133-L147 |
238,475 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.add_node | def add_node(self, node):
"""Add a new node to the scheduler.
From now on the node will be assigned work units to be executed.
Called by the ``DSession.worker_workerready`` hook when it successfully
bootstraps a new node.
"""
assert node not in self.assigned_work
self.assigned_work[node] = OrderedDict() | python | def add_node(self, node):
assert node not in self.assigned_work
self.assigned_work[node] = OrderedDict() | [
"def",
"add_node",
"(",
"self",
",",
"node",
")",
":",
"assert",
"node",
"not",
"in",
"self",
".",
"assigned_work",
"self",
".",
"assigned_work",
"[",
"node",
"]",
"=",
"OrderedDict",
"(",
")"
] | Add a new node to the scheduler.
From now on the node will be assigned work units to be executed.
Called by the ``DSession.worker_workerready`` hook when it successfully
bootstraps a new node. | [
"Add",
"a",
"new",
"node",
"to",
"the",
"scheduler",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L149-L158 |
238,476 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.remove_node | def remove_node(self, node):
"""Remove a node from the scheduler.
This should be called either when the node crashed or at shutdown time.
In the former case any pending items assigned to the node will be
re-scheduled.
Called by the hooks:
- ``DSession.worker_workerfinished``.
- ``DSession.worker_errordown``.
Return the item being executed while the node crashed or None if the
node has no more pending items.
"""
workload = self.assigned_work.pop(node)
if not self._pending_of(workload):
return None
# The node crashed, identify test that crashed
for work_unit in workload.values():
for nodeid, completed in work_unit.items():
if not completed:
crashitem = nodeid
break
else:
continue
break
else:
raise RuntimeError(
"Unable to identify crashitem on a workload with pending items"
)
# Made uncompleted work unit available again
self.workqueue.update(workload)
for node in self.assigned_work:
self._reschedule(node)
return crashitem | python | def remove_node(self, node):
workload = self.assigned_work.pop(node)
if not self._pending_of(workload):
return None
# The node crashed, identify test that crashed
for work_unit in workload.values():
for nodeid, completed in work_unit.items():
if not completed:
crashitem = nodeid
break
else:
continue
break
else:
raise RuntimeError(
"Unable to identify crashitem on a workload with pending items"
)
# Made uncompleted work unit available again
self.workqueue.update(workload)
for node in self.assigned_work:
self._reschedule(node)
return crashitem | [
"def",
"remove_node",
"(",
"self",
",",
"node",
")",
":",
"workload",
"=",
"self",
".",
"assigned_work",
".",
"pop",
"(",
"node",
")",
"if",
"not",
"self",
".",
"_pending_of",
"(",
"workload",
")",
":",
"return",
"None",
"# The node crashed, identify test th... | Remove a node from the scheduler.
This should be called either when the node crashed or at shutdown time.
In the former case any pending items assigned to the node will be
re-scheduled.
Called by the hooks:
- ``DSession.worker_workerfinished``.
- ``DSession.worker_errordown``.
Return the item being executed while the node crashed or None if the
node has no more pending items. | [
"Remove",
"a",
"node",
"from",
"the",
"scheduler",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L160-L199 |
238,477 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.add_node_collection | def add_node_collection(self, node, collection):
"""Add the collected test items from a node.
The collection is stored in the ``.registered_collections`` dictionary.
Called by the hook:
- ``DSession.worker_collectionfinish``.
"""
# Check that add_node() was called on the node before
assert node in self.assigned_work
# A new node has been added later, perhaps an original one died.
if self.collection_is_completed:
# Assert that .schedule() should have been called by now
assert self.collection
# Check that the new collection matches the official collection
if collection != self.collection:
other_node = next(iter(self.registered_collections.keys()))
msg = report_collection_diff(
self.collection, collection, other_node.gateway.id, node.gateway.id
)
self.log(msg)
return
self.registered_collections[node] = list(collection) | python | def add_node_collection(self, node, collection):
# Check that add_node() was called on the node before
assert node in self.assigned_work
# A new node has been added later, perhaps an original one died.
if self.collection_is_completed:
# Assert that .schedule() should have been called by now
assert self.collection
# Check that the new collection matches the official collection
if collection != self.collection:
other_node = next(iter(self.registered_collections.keys()))
msg = report_collection_diff(
self.collection, collection, other_node.gateway.id, node.gateway.id
)
self.log(msg)
return
self.registered_collections[node] = list(collection) | [
"def",
"add_node_collection",
"(",
"self",
",",
"node",
",",
"collection",
")",
":",
"# Check that add_node() was called on the node before",
"assert",
"node",
"in",
"self",
".",
"assigned_work",
"# A new node has been added later, perhaps an original one died.",
"if",
"self",
... | Add the collected test items from a node.
The collection is stored in the ``.registered_collections`` dictionary.
Called by the hook:
- ``DSession.worker_collectionfinish``. | [
"Add",
"the",
"collected",
"test",
"items",
"from",
"a",
"node",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L201-L231 |
238,478 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling._assign_work_unit | def _assign_work_unit(self, node):
"""Assign a work unit to a node."""
assert self.workqueue
# Grab a unit of work
scope, work_unit = self.workqueue.popitem(last=False)
# Keep track of the assigned work
assigned_to_node = self.assigned_work.setdefault(node, default=OrderedDict())
assigned_to_node[scope] = work_unit
# Ask the node to execute the workload
worker_collection = self.registered_collections[node]
nodeids_indexes = [
worker_collection.index(nodeid)
for nodeid, completed in work_unit.items()
if not completed
]
node.send_runtest_some(nodeids_indexes) | python | def _assign_work_unit(self, node):
assert self.workqueue
# Grab a unit of work
scope, work_unit = self.workqueue.popitem(last=False)
# Keep track of the assigned work
assigned_to_node = self.assigned_work.setdefault(node, default=OrderedDict())
assigned_to_node[scope] = work_unit
# Ask the node to execute the workload
worker_collection = self.registered_collections[node]
nodeids_indexes = [
worker_collection.index(nodeid)
for nodeid, completed in work_unit.items()
if not completed
]
node.send_runtest_some(nodeids_indexes) | [
"def",
"_assign_work_unit",
"(",
"self",
",",
"node",
")",
":",
"assert",
"self",
".",
"workqueue",
"# Grab a unit of work",
"scope",
",",
"work_unit",
"=",
"self",
".",
"workqueue",
".",
"popitem",
"(",
"last",
"=",
"False",
")",
"# Keep track of the assigned w... | Assign a work unit to a node. | [
"Assign",
"a",
"work",
"unit",
"to",
"a",
"node",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L246-L265 |
238,479 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling._pending_of | def _pending_of(self, workload):
"""Return the number of pending tests in a workload."""
pending = sum(list(scope.values()).count(False) for scope in workload.values())
return pending | python | def _pending_of(self, workload):
pending = sum(list(scope.values()).count(False) for scope in workload.values())
return pending | [
"def",
"_pending_of",
"(",
"self",
",",
"workload",
")",
":",
"pending",
"=",
"sum",
"(",
"list",
"(",
"scope",
".",
"values",
"(",
")",
")",
".",
"count",
"(",
"False",
")",
"for",
"scope",
"in",
"workload",
".",
"values",
"(",
")",
")",
"return",... | Return the number of pending tests in a workload. | [
"Return",
"the",
"number",
"of",
"pending",
"tests",
"in",
"a",
"workload",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L291-L294 |
238,480 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling._reschedule | def _reschedule(self, node):
"""Maybe schedule new items on the node.
If there are any globally pending work units left then this will check
if the given node should be given any more tests.
"""
# Do not add more work to a node shutting down
if node.shutting_down:
return
# Check that more work is available
if not self.workqueue:
node.shutdown()
return
self.log("Number of units waiting for node:", len(self.workqueue))
# Check that the node is almost depleted of work
# 2: Heuristic of minimum tests to enqueue more work
if self._pending_of(self.assigned_work[node]) > 2:
return
# Pop one unit of work and assign it
self._assign_work_unit(node) | python | def _reschedule(self, node):
# Do not add more work to a node shutting down
if node.shutting_down:
return
# Check that more work is available
if not self.workqueue:
node.shutdown()
return
self.log("Number of units waiting for node:", len(self.workqueue))
# Check that the node is almost depleted of work
# 2: Heuristic of minimum tests to enqueue more work
if self._pending_of(self.assigned_work[node]) > 2:
return
# Pop one unit of work and assign it
self._assign_work_unit(node) | [
"def",
"_reschedule",
"(",
"self",
",",
"node",
")",
":",
"# Do not add more work to a node shutting down",
"if",
"node",
".",
"shutting_down",
":",
"return",
"# Check that more work is available",
"if",
"not",
"self",
".",
"workqueue",
":",
"node",
".",
"shutdown",
... | Maybe schedule new items on the node.
If there are any globally pending work units left then this will check
if the given node should be given any more tests. | [
"Maybe",
"schedule",
"new",
"items",
"on",
"the",
"node",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L296-L320 |
238,481 | pytest-dev/pytest-xdist | xdist/scheduler/loadscope.py | LoadScopeScheduling.schedule | def schedule(self):
"""Initiate distribution of the test collection.
Initiate scheduling of the items across the nodes. If this gets called
again later it behaves the same as calling ``._reschedule()`` on all
nodes so that newly added nodes will start to be used.
If ``.collection_is_completed`` is True, this is called by the hook:
- ``DSession.worker_collectionfinish``.
"""
assert self.collection_is_completed
# Initial distribution already happened, reschedule on all nodes
if self.collection is not None:
for node in self.nodes:
self._reschedule(node)
return
# Check that all nodes collected the same tests
if not self._check_nodes_have_same_collection():
self.log("**Different tests collected, aborting run**")
return
# Collections are identical, create the final list of items
self.collection = list(next(iter(self.registered_collections.values())))
if not self.collection:
return
# Determine chunks of work (scopes)
for nodeid in self.collection:
scope = self._split_scope(nodeid)
work_unit = self.workqueue.setdefault(scope, default=OrderedDict())
work_unit[nodeid] = False
# Avoid having more workers than work
extra_nodes = len(self.nodes) - len(self.workqueue)
if extra_nodes > 0:
self.log("Shuting down {0} nodes".format(extra_nodes))
for _ in range(extra_nodes):
unused_node, assigned = self.assigned_work.popitem(last=True)
self.log("Shuting down unused node {0}".format(unused_node))
unused_node.shutdown()
# Assign initial workload
for node in self.nodes:
self._assign_work_unit(node)
# Ensure nodes start with at least two work units if possible (#277)
for node in self.nodes:
self._reschedule(node)
# Initial distribution sent all tests, start node shutdown
if not self.workqueue:
for node in self.nodes:
node.shutdown() | python | def schedule(self):
assert self.collection_is_completed
# Initial distribution already happened, reschedule on all nodes
if self.collection is not None:
for node in self.nodes:
self._reschedule(node)
return
# Check that all nodes collected the same tests
if not self._check_nodes_have_same_collection():
self.log("**Different tests collected, aborting run**")
return
# Collections are identical, create the final list of items
self.collection = list(next(iter(self.registered_collections.values())))
if not self.collection:
return
# Determine chunks of work (scopes)
for nodeid in self.collection:
scope = self._split_scope(nodeid)
work_unit = self.workqueue.setdefault(scope, default=OrderedDict())
work_unit[nodeid] = False
# Avoid having more workers than work
extra_nodes = len(self.nodes) - len(self.workqueue)
if extra_nodes > 0:
self.log("Shuting down {0} nodes".format(extra_nodes))
for _ in range(extra_nodes):
unused_node, assigned = self.assigned_work.popitem(last=True)
self.log("Shuting down unused node {0}".format(unused_node))
unused_node.shutdown()
# Assign initial workload
for node in self.nodes:
self._assign_work_unit(node)
# Ensure nodes start with at least two work units if possible (#277)
for node in self.nodes:
self._reschedule(node)
# Initial distribution sent all tests, start node shutdown
if not self.workqueue:
for node in self.nodes:
node.shutdown() | [
"def",
"schedule",
"(",
"self",
")",
":",
"assert",
"self",
".",
"collection_is_completed",
"# Initial distribution already happened, reschedule on all nodes",
"if",
"self",
".",
"collection",
"is",
"not",
"None",
":",
"for",
"node",
"in",
"self",
".",
"nodes",
":",... | Initiate distribution of the test collection.
Initiate scheduling of the items across the nodes. If this gets called
again later it behaves the same as calling ``._reschedule()`` on all
nodes so that newly added nodes will start to be used.
If ``.collection_is_completed`` is True, this is called by the hook:
- ``DSession.worker_collectionfinish``. | [
"Initiate",
"distribution",
"of",
"the",
"test",
"collection",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L322-L380 |
238,482 | pytest-dev/pytest-xdist | xdist/scheduler/each.py | EachScheduling.schedule | def schedule(self):
"""Schedule the test items on the nodes
If the node's pending list is empty it is a new node which
needs to run all the tests. If the pending list is already
populated (by ``.add_node_collection()``) then it replaces a
dead node and we only need to run those tests.
"""
assert self.collection_is_completed
for node, pending in self.node2pending.items():
if node in self._started:
continue
if not pending:
pending[:] = range(len(self.node2collection[node]))
node.send_runtest_all()
node.shutdown()
else:
node.send_runtest_some(pending)
self._started.append(node) | python | def schedule(self):
assert self.collection_is_completed
for node, pending in self.node2pending.items():
if node in self._started:
continue
if not pending:
pending[:] = range(len(self.node2collection[node]))
node.send_runtest_all()
node.shutdown()
else:
node.send_runtest_some(pending)
self._started.append(node) | [
"def",
"schedule",
"(",
"self",
")",
":",
"assert",
"self",
".",
"collection_is_completed",
"for",
"node",
",",
"pending",
"in",
"self",
".",
"node2pending",
".",
"items",
"(",
")",
":",
"if",
"node",
"in",
"self",
".",
"_started",
":",
"continue",
"if",... | Schedule the test items on the nodes
If the node's pending list is empty it is a new node which
needs to run all the tests. If the pending list is already
populated (by ``.add_node_collection()``) then it replaces a
dead node and we only need to run those tests. | [
"Schedule",
"the",
"test",
"items",
"on",
"the",
"nodes"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/each.py#L114-L132 |
238,483 | pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling.has_pending | def has_pending(self):
"""Return True if there are pending test items
This indicates that collection has finished and nodes are
still processing test items, so this can be thought of as
"the scheduler is active".
"""
if self.pending:
return True
for pending in self.node2pending.values():
if pending:
return True
return False | python | def has_pending(self):
if self.pending:
return True
for pending in self.node2pending.values():
if pending:
return True
return False | [
"def",
"has_pending",
"(",
"self",
")",
":",
"if",
"self",
".",
"pending",
":",
"return",
"True",
"for",
"pending",
"in",
"self",
".",
"node2pending",
".",
"values",
"(",
")",
":",
"if",
"pending",
":",
"return",
"True",
"return",
"False"
] | Return True if there are pending test items
This indicates that collection has finished and nodes are
still processing test items, so this can be thought of as
"the scheduler is active". | [
"Return",
"True",
"if",
"there",
"are",
"pending",
"test",
"items"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L96-L108 |
238,484 | pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling.check_schedule | def check_schedule(self, node, duration=0):
"""Maybe schedule new items on the node
If there are any globally pending nodes left then this will
check if the given node should be given any more tests. The
``duration`` of the last test is optionally used as a
heuristic to influence how many tests the node is assigned.
"""
if node.shutting_down:
return
if self.pending:
# how many nodes do we have?
num_nodes = len(self.node2pending)
# if our node goes below a heuristic minimum, fill it out to
# heuristic maximum
items_per_node_min = max(2, len(self.pending) // num_nodes // 4)
items_per_node_max = max(2, len(self.pending) // num_nodes // 2)
node_pending = self.node2pending[node]
if len(node_pending) < items_per_node_min:
if duration >= 0.1 and len(node_pending) >= 2:
# seems the node is doing long-running tests
# and has enough items to continue
# so let's rather wait with sending new items
return
num_send = items_per_node_max - len(node_pending)
self._send_tests(node, num_send)
else:
node.shutdown()
self.log("num items waiting for node:", len(self.pending)) | python | def check_schedule(self, node, duration=0):
if node.shutting_down:
return
if self.pending:
# how many nodes do we have?
num_nodes = len(self.node2pending)
# if our node goes below a heuristic minimum, fill it out to
# heuristic maximum
items_per_node_min = max(2, len(self.pending) // num_nodes // 4)
items_per_node_max = max(2, len(self.pending) // num_nodes // 2)
node_pending = self.node2pending[node]
if len(node_pending) < items_per_node_min:
if duration >= 0.1 and len(node_pending) >= 2:
# seems the node is doing long-running tests
# and has enough items to continue
# so let's rather wait with sending new items
return
num_send = items_per_node_max - len(node_pending)
self._send_tests(node, num_send)
else:
node.shutdown()
self.log("num items waiting for node:", len(self.pending)) | [
"def",
"check_schedule",
"(",
"self",
",",
"node",
",",
"duration",
"=",
"0",
")",
":",
"if",
"node",
".",
"shutting_down",
":",
"return",
"if",
"self",
".",
"pending",
":",
"# how many nodes do we have?",
"num_nodes",
"=",
"len",
"(",
"self",
".",
"node2p... | Maybe schedule new items on the node
If there are any globally pending nodes left then this will
check if the given node should be given any more tests. The
``duration`` of the last test is optionally used as a
heuristic to influence how many tests the node is assigned. | [
"Maybe",
"schedule",
"new",
"items",
"on",
"the",
"node"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L154-L184 |
238,485 | pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling.remove_node | def remove_node(self, node):
"""Remove a node from the scheduler
This should be called either when the node crashed or at
shutdown time. In the former case any pending items assigned
to the node will be re-scheduled. Called by the
``DSession.worker_workerfinished`` and
``DSession.worker_errordown`` hooks.
Return the item which was being executing while the node
crashed or None if the node has no more pending items.
"""
pending = self.node2pending.pop(node)
if not pending:
return
# The node crashed, reassing pending items
crashitem = self.collection[pending.pop(0)]
self.pending.extend(pending)
for node in self.node2pending:
self.check_schedule(node)
return crashitem | python | def remove_node(self, node):
pending = self.node2pending.pop(node)
if not pending:
return
# The node crashed, reassing pending items
crashitem = self.collection[pending.pop(0)]
self.pending.extend(pending)
for node in self.node2pending:
self.check_schedule(node)
return crashitem | [
"def",
"remove_node",
"(",
"self",
",",
"node",
")",
":",
"pending",
"=",
"self",
".",
"node2pending",
".",
"pop",
"(",
"node",
")",
"if",
"not",
"pending",
":",
"return",
"# The node crashed, reassing pending items",
"crashitem",
"=",
"self",
".",
"collection... | Remove a node from the scheduler
This should be called either when the node crashed or at
shutdown time. In the former case any pending items assigned
to the node will be re-scheduled. Called by the
``DSession.worker_workerfinished`` and
``DSession.worker_errordown`` hooks.
Return the item which was being executing while the node
crashed or None if the node has no more pending items. | [
"Remove",
"a",
"node",
"from",
"the",
"scheduler"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L186-L208 |
238,486 | pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling.schedule | def schedule(self):
"""Initiate distribution of the test collection
Initiate scheduling of the items across the nodes. If this
gets called again later it behaves the same as calling
``.check_schedule()`` on all nodes so that newly added nodes
will start to be used.
This is called by the ``DSession.worker_collectionfinish`` hook
if ``.collection_is_completed`` is True.
"""
assert self.collection_is_completed
# Initial distribution already happened, reschedule on all nodes
if self.collection is not None:
for node in self.nodes:
self.check_schedule(node)
return
# XXX allow nodes to have different collections
if not self._check_nodes_have_same_collection():
self.log("**Different tests collected, aborting run**")
return
# Collections are identical, create the index of pending items.
self.collection = list(self.node2collection.values())[0]
self.pending[:] = range(len(self.collection))
if not self.collection:
return
# Send a batch of tests to run. If we don't have at least two
# tests per node, we have to send them all so that we can send
# shutdown signals and get all nodes working.
initial_batch = max(len(self.pending) // 4, 2 * len(self.nodes))
# distribute tests round-robin up to the batch size
# (or until we run out)
nodes = cycle(self.nodes)
for i in range(initial_batch):
self._send_tests(next(nodes), 1)
if not self.pending:
# initial distribution sent all tests, start node shutdown
for node in self.nodes:
node.shutdown() | python | def schedule(self):
assert self.collection_is_completed
# Initial distribution already happened, reschedule on all nodes
if self.collection is not None:
for node in self.nodes:
self.check_schedule(node)
return
# XXX allow nodes to have different collections
if not self._check_nodes_have_same_collection():
self.log("**Different tests collected, aborting run**")
return
# Collections are identical, create the index of pending items.
self.collection = list(self.node2collection.values())[0]
self.pending[:] = range(len(self.collection))
if not self.collection:
return
# Send a batch of tests to run. If we don't have at least two
# tests per node, we have to send them all so that we can send
# shutdown signals and get all nodes working.
initial_batch = max(len(self.pending) // 4, 2 * len(self.nodes))
# distribute tests round-robin up to the batch size
# (or until we run out)
nodes = cycle(self.nodes)
for i in range(initial_batch):
self._send_tests(next(nodes), 1)
if not self.pending:
# initial distribution sent all tests, start node shutdown
for node in self.nodes:
node.shutdown() | [
"def",
"schedule",
"(",
"self",
")",
":",
"assert",
"self",
".",
"collection_is_completed",
"# Initial distribution already happened, reschedule on all nodes",
"if",
"self",
".",
"collection",
"is",
"not",
"None",
":",
"for",
"node",
"in",
"self",
".",
"nodes",
":",... | Initiate distribution of the test collection
Initiate scheduling of the items across the nodes. If this
gets called again later it behaves the same as calling
``.check_schedule()`` on all nodes so that newly added nodes
will start to be used.
This is called by the ``DSession.worker_collectionfinish`` hook
if ``.collection_is_completed`` is True. | [
"Initiate",
"distribution",
"of",
"the",
"test",
"collection"
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L210-L254 |
238,487 | pytest-dev/pytest-xdist | xdist/scheduler/load.py | LoadScheduling._check_nodes_have_same_collection | def _check_nodes_have_same_collection(self):
"""Return True if all nodes have collected the same items.
If collections differ, this method returns False while logging
the collection differences and posting collection errors to
pytest_collectreport hook.
"""
node_collection_items = list(self.node2collection.items())
first_node, col = node_collection_items[0]
same_collection = True
for node, collection in node_collection_items[1:]:
msg = report_collection_diff(
col, collection, first_node.gateway.id, node.gateway.id
)
if msg:
same_collection = False
self.log(msg)
if self.config is not None:
rep = CollectReport(
node.gateway.id, "failed", longrepr=msg, result=[]
)
self.config.hook.pytest_collectreport(report=rep)
return same_collection | python | def _check_nodes_have_same_collection(self):
node_collection_items = list(self.node2collection.items())
first_node, col = node_collection_items[0]
same_collection = True
for node, collection in node_collection_items[1:]:
msg = report_collection_diff(
col, collection, first_node.gateway.id, node.gateway.id
)
if msg:
same_collection = False
self.log(msg)
if self.config is not None:
rep = CollectReport(
node.gateway.id, "failed", longrepr=msg, result=[]
)
self.config.hook.pytest_collectreport(report=rep)
return same_collection | [
"def",
"_check_nodes_have_same_collection",
"(",
"self",
")",
":",
"node_collection_items",
"=",
"list",
"(",
"self",
".",
"node2collection",
".",
"items",
"(",
")",
")",
"first_node",
",",
"col",
"=",
"node_collection_items",
"[",
"0",
"]",
"same_collection",
"... | Return True if all nodes have collected the same items.
If collections differ, this method returns False while logging
the collection differences and posting collection errors to
pytest_collectreport hook. | [
"Return",
"True",
"if",
"all",
"nodes",
"have",
"collected",
"the",
"same",
"items",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/load.py#L263-L286 |
238,488 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.loop_once | def loop_once(self):
"""Process one callback from one of the workers."""
while 1:
if not self._active_nodes:
# If everything has died stop looping
self.triggershutdown()
raise RuntimeError("Unexpectedly no active workers available")
try:
eventcall = self.queue.get(timeout=2.0)
break
except Empty:
continue
callname, kwargs = eventcall
assert callname, kwargs
method = "worker_" + callname
call = getattr(self, method)
self.log("calling method", method, kwargs)
call(**kwargs)
if self.sched.tests_finished:
self.triggershutdown() | python | def loop_once(self):
while 1:
if not self._active_nodes:
# If everything has died stop looping
self.triggershutdown()
raise RuntimeError("Unexpectedly no active workers available")
try:
eventcall = self.queue.get(timeout=2.0)
break
except Empty:
continue
callname, kwargs = eventcall
assert callname, kwargs
method = "worker_" + callname
call = getattr(self, method)
self.log("calling method", method, kwargs)
call(**kwargs)
if self.sched.tests_finished:
self.triggershutdown() | [
"def",
"loop_once",
"(",
"self",
")",
":",
"while",
"1",
":",
"if",
"not",
"self",
".",
"_active_nodes",
":",
"# If everything has died stop looping",
"self",
".",
"triggershutdown",
"(",
")",
"raise",
"RuntimeError",
"(",
"\"Unexpectedly no active workers available\"... | Process one callback from one of the workers. | [
"Process",
"one",
"callback",
"from",
"one",
"of",
"the",
"workers",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L121-L140 |
238,489 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_workerready | def worker_workerready(self, node, workerinfo):
"""Emitted when a node first starts up.
This adds the node to the scheduler, nodes continue with
collection without any further input.
"""
node.workerinfo = workerinfo
node.workerinfo["id"] = node.gateway.id
node.workerinfo["spec"] = node.gateway.spec
# TODO: (#234 task) needs this for pytest. Remove when refactor in pytest repo
node.slaveinfo = node.workerinfo
self.config.hook.pytest_testnodeready(node=node)
if self.shuttingdown:
node.shutdown()
else:
self.sched.add_node(node) | python | def worker_workerready(self, node, workerinfo):
node.workerinfo = workerinfo
node.workerinfo["id"] = node.gateway.id
node.workerinfo["spec"] = node.gateway.spec
# TODO: (#234 task) needs this for pytest. Remove when refactor in pytest repo
node.slaveinfo = node.workerinfo
self.config.hook.pytest_testnodeready(node=node)
if self.shuttingdown:
node.shutdown()
else:
self.sched.add_node(node) | [
"def",
"worker_workerready",
"(",
"self",
",",
"node",
",",
"workerinfo",
")",
":",
"node",
".",
"workerinfo",
"=",
"workerinfo",
"node",
".",
"workerinfo",
"[",
"\"id\"",
"]",
"=",
"node",
".",
"gateway",
".",
"id",
"node",
".",
"workerinfo",
"[",
"\"sp... | Emitted when a node first starts up.
This adds the node to the scheduler, nodes continue with
collection without any further input. | [
"Emitted",
"when",
"a",
"node",
"first",
"starts",
"up",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L146-L163 |
238,490 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_workerfinished | def worker_workerfinished(self, node):
"""Emitted when node executes its pytest_sessionfinish hook.
Removes the node from the scheduler.
The node might not be in the scheduler if it had not emitted
workerready before shutdown was triggered.
"""
self.config.hook.pytest_testnodedown(node=node, error=None)
if node.workeroutput["exitstatus"] == 2: # keyboard-interrupt
self.shouldstop = "%s received keyboard-interrupt" % (node,)
self.worker_errordown(node, "keyboard-interrupt")
return
if node in self.sched.nodes:
crashitem = self.sched.remove_node(node)
assert not crashitem, (crashitem, node)
self._active_nodes.remove(node) | python | def worker_workerfinished(self, node):
self.config.hook.pytest_testnodedown(node=node, error=None)
if node.workeroutput["exitstatus"] == 2: # keyboard-interrupt
self.shouldstop = "%s received keyboard-interrupt" % (node,)
self.worker_errordown(node, "keyboard-interrupt")
return
if node in self.sched.nodes:
crashitem = self.sched.remove_node(node)
assert not crashitem, (crashitem, node)
self._active_nodes.remove(node) | [
"def",
"worker_workerfinished",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"config",
".",
"hook",
".",
"pytest_testnodedown",
"(",
"node",
"=",
"node",
",",
"error",
"=",
"None",
")",
"if",
"node",
".",
"workeroutput",
"[",
"\"exitstatus\"",
"]",
"... | Emitted when node executes its pytest_sessionfinish hook.
Removes the node from the scheduler.
The node might not be in the scheduler if it had not emitted
workerready before shutdown was triggered. | [
"Emitted",
"when",
"node",
"executes",
"its",
"pytest_sessionfinish",
"hook",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L165-L181 |
238,491 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_errordown | def worker_errordown(self, node, error):
"""Emitted by the WorkerController when a node dies."""
self.config.hook.pytest_testnodedown(node=node, error=error)
try:
crashitem = self.sched.remove_node(node)
except KeyError:
pass
else:
if crashitem:
self.handle_crashitem(crashitem, node)
self._failed_nodes_count += 1
maximum_reached = (
self._max_worker_restart is not None
and self._failed_nodes_count > self._max_worker_restart
)
if maximum_reached:
if self._max_worker_restart == 0:
msg = "Worker restarting disabled"
else:
msg = "Maximum crashed workers reached: %d" % self._max_worker_restart
self.report_line(msg)
else:
self.report_line("Replacing crashed worker %s" % node.gateway.id)
self._clone_node(node)
self._active_nodes.remove(node) | python | def worker_errordown(self, node, error):
self.config.hook.pytest_testnodedown(node=node, error=error)
try:
crashitem = self.sched.remove_node(node)
except KeyError:
pass
else:
if crashitem:
self.handle_crashitem(crashitem, node)
self._failed_nodes_count += 1
maximum_reached = (
self._max_worker_restart is not None
and self._failed_nodes_count > self._max_worker_restart
)
if maximum_reached:
if self._max_worker_restart == 0:
msg = "Worker restarting disabled"
else:
msg = "Maximum crashed workers reached: %d" % self._max_worker_restart
self.report_line(msg)
else:
self.report_line("Replacing crashed worker %s" % node.gateway.id)
self._clone_node(node)
self._active_nodes.remove(node) | [
"def",
"worker_errordown",
"(",
"self",
",",
"node",
",",
"error",
")",
":",
"self",
".",
"config",
".",
"hook",
".",
"pytest_testnodedown",
"(",
"node",
"=",
"node",
",",
"error",
"=",
"error",
")",
"try",
":",
"crashitem",
"=",
"self",
".",
"sched",
... | Emitted by the WorkerController when a node dies. | [
"Emitted",
"by",
"the",
"WorkerController",
"when",
"a",
"node",
"dies",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L183-L208 |
238,492 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_collectionfinish | def worker_collectionfinish(self, node, ids):
"""worker has finished test collection.
This adds the collection for this node to the scheduler. If
the scheduler indicates collection is finished (i.e. all
initial nodes have submitted their collections), then tells the
scheduler to schedule the collected items. When initiating
scheduling the first time it logs which scheduler is in use.
"""
if self.shuttingdown:
return
self.config.hook.pytest_xdist_node_collection_finished(node=node, ids=ids)
# tell session which items were effectively collected otherwise
# the master node will finish the session with EXIT_NOTESTSCOLLECTED
self._session.testscollected = len(ids)
self.sched.add_node_collection(node, ids)
if self.terminal:
self.trdist.setstatus(node.gateway.spec, "[%d]" % (len(ids)))
if self.sched.collection_is_completed:
if self.terminal and not self.sched.has_pending:
self.trdist.ensure_show_status()
self.terminal.write_line("")
if self.config.option.verbose > 0:
self.terminal.write_line(
"scheduling tests via %s" % (self.sched.__class__.__name__)
)
self.sched.schedule() | python | def worker_collectionfinish(self, node, ids):
if self.shuttingdown:
return
self.config.hook.pytest_xdist_node_collection_finished(node=node, ids=ids)
# tell session which items were effectively collected otherwise
# the master node will finish the session with EXIT_NOTESTSCOLLECTED
self._session.testscollected = len(ids)
self.sched.add_node_collection(node, ids)
if self.terminal:
self.trdist.setstatus(node.gateway.spec, "[%d]" % (len(ids)))
if self.sched.collection_is_completed:
if self.terminal and not self.sched.has_pending:
self.trdist.ensure_show_status()
self.terminal.write_line("")
if self.config.option.verbose > 0:
self.terminal.write_line(
"scheduling tests via %s" % (self.sched.__class__.__name__)
)
self.sched.schedule() | [
"def",
"worker_collectionfinish",
"(",
"self",
",",
"node",
",",
"ids",
")",
":",
"if",
"self",
".",
"shuttingdown",
":",
"return",
"self",
".",
"config",
".",
"hook",
".",
"pytest_xdist_node_collection_finished",
"(",
"node",
"=",
"node",
",",
"ids",
"=",
... | worker has finished test collection.
This adds the collection for this node to the scheduler. If
the scheduler indicates collection is finished (i.e. all
initial nodes have submitted their collections), then tells the
scheduler to schedule the collected items. When initiating
scheduling the first time it logs which scheduler is in use. | [
"worker",
"has",
"finished",
"test",
"collection",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L210-L236 |
238,493 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_logstart | def worker_logstart(self, node, nodeid, location):
"""Emitted when a node calls the pytest_runtest_logstart hook."""
self.config.hook.pytest_runtest_logstart(nodeid=nodeid, location=location) | python | def worker_logstart(self, node, nodeid, location):
self.config.hook.pytest_runtest_logstart(nodeid=nodeid, location=location) | [
"def",
"worker_logstart",
"(",
"self",
",",
"node",
",",
"nodeid",
",",
"location",
")",
":",
"self",
".",
"config",
".",
"hook",
".",
"pytest_runtest_logstart",
"(",
"nodeid",
"=",
"nodeid",
",",
"location",
"=",
"location",
")"
] | Emitted when a node calls the pytest_runtest_logstart hook. | [
"Emitted",
"when",
"a",
"node",
"calls",
"the",
"pytest_runtest_logstart",
"hook",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L238-L240 |
238,494 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_logfinish | def worker_logfinish(self, node, nodeid, location):
"""Emitted when a node calls the pytest_runtest_logfinish hook."""
self.config.hook.pytest_runtest_logfinish(nodeid=nodeid, location=location) | python | def worker_logfinish(self, node, nodeid, location):
self.config.hook.pytest_runtest_logfinish(nodeid=nodeid, location=location) | [
"def",
"worker_logfinish",
"(",
"self",
",",
"node",
",",
"nodeid",
",",
"location",
")",
":",
"self",
".",
"config",
".",
"hook",
".",
"pytest_runtest_logfinish",
"(",
"nodeid",
"=",
"nodeid",
",",
"location",
"=",
"location",
")"
] | Emitted when a node calls the pytest_runtest_logfinish hook. | [
"Emitted",
"when",
"a",
"node",
"calls",
"the",
"pytest_runtest_logfinish",
"hook",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L242-L244 |
238,495 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession.worker_collectreport | def worker_collectreport(self, node, rep):
"""Emitted when a node calls the pytest_collectreport hook.
Because we only need the report when there's a failure/skip, as optimization
we only expect to receive failed/skipped reports from workers (#330).
"""
assert not rep.passed
self._failed_worker_collectreport(node, rep) | python | def worker_collectreport(self, node, rep):
assert not rep.passed
self._failed_worker_collectreport(node, rep) | [
"def",
"worker_collectreport",
"(",
"self",
",",
"node",
",",
"rep",
")",
":",
"assert",
"not",
"rep",
".",
"passed",
"self",
".",
"_failed_worker_collectreport",
"(",
"node",
",",
"rep",
")"
] | Emitted when a node calls the pytest_collectreport hook.
Because we only need the report when there's a failure/skip, as optimization
we only expect to receive failed/skipped reports from workers (#330). | [
"Emitted",
"when",
"a",
"node",
"calls",
"the",
"pytest_collectreport",
"hook",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L260-L267 |
238,496 | pytest-dev/pytest-xdist | xdist/dsession.py | DSession._clone_node | def _clone_node(self, node):
"""Return new node based on an existing one.
This is normally for when a node dies, this will copy the spec
of the existing node and create a new one with a new id. The
new node will have been setup so it will start calling the
"worker_*" hooks and do work soon.
"""
spec = node.gateway.spec
spec.id = None
self.nodemanager.group.allocate_id(spec)
node = self.nodemanager.setup_node(spec, self.queue.put)
self._active_nodes.add(node)
return node | python | def _clone_node(self, node):
spec = node.gateway.spec
spec.id = None
self.nodemanager.group.allocate_id(spec)
node = self.nodemanager.setup_node(spec, self.queue.put)
self._active_nodes.add(node)
return node | [
"def",
"_clone_node",
"(",
"self",
",",
"node",
")",
":",
"spec",
"=",
"node",
".",
"gateway",
".",
"spec",
"spec",
".",
"id",
"=",
"None",
"self",
".",
"nodemanager",
".",
"group",
".",
"allocate_id",
"(",
"spec",
")",
"node",
"=",
"self",
".",
"n... | Return new node based on an existing one.
This is normally for when a node dies, this will copy the spec
of the existing node and create a new one with a new id. The
new node will have been setup so it will start calling the
"worker_*" hooks and do work soon. | [
"Return",
"new",
"node",
"based",
"on",
"an",
"existing",
"one",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/dsession.py#L279-L292 |
238,497 | pytest-dev/pytest-xdist | xdist/workermanage.py | NodeManager.rsync_roots | def rsync_roots(self, gateway):
"""Rsync the set of roots to the node's gateway cwd."""
if self.roots:
for root in self.roots:
self.rsync(gateway, root, **self.rsyncoptions) | python | def rsync_roots(self, gateway):
if self.roots:
for root in self.roots:
self.rsync(gateway, root, **self.rsyncoptions) | [
"def",
"rsync_roots",
"(",
"self",
",",
"gateway",
")",
":",
"if",
"self",
".",
"roots",
":",
"for",
"root",
"in",
"self",
".",
"roots",
":",
"self",
".",
"rsync",
"(",
"gateway",
",",
"root",
",",
"*",
"*",
"self",
".",
"rsyncoptions",
")"
] | Rsync the set of roots to the node's gateway cwd. | [
"Rsync",
"the",
"set",
"of",
"roots",
"to",
"the",
"node",
"s",
"gateway",
"cwd",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L53-L57 |
238,498 | pytest-dev/pytest-xdist | xdist/workermanage.py | NodeManager._getrsyncoptions | def _getrsyncoptions(self):
"""Get options to be passed for rsync."""
ignores = list(self.DEFAULT_IGNORES)
ignores += self.config.option.rsyncignore
ignores += self.config.getini("rsyncignore")
return {"ignores": ignores, "verbose": self.config.option.verbose} | python | def _getrsyncoptions(self):
ignores = list(self.DEFAULT_IGNORES)
ignores += self.config.option.rsyncignore
ignores += self.config.getini("rsyncignore")
return {"ignores": ignores, "verbose": self.config.option.verbose} | [
"def",
"_getrsyncoptions",
"(",
"self",
")",
":",
"ignores",
"=",
"list",
"(",
"self",
".",
"DEFAULT_IGNORES",
")",
"ignores",
"+=",
"self",
".",
"config",
".",
"option",
".",
"rsyncignore",
"ignores",
"+=",
"self",
".",
"config",
".",
"getini",
"(",
"\"... | Get options to be passed for rsync. | [
"Get",
"options",
"to",
"be",
"passed",
"for",
"rsync",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L109-L115 |
238,499 | pytest-dev/pytest-xdist | xdist/workermanage.py | WorkerController.sendcommand | def sendcommand(self, name, **kwargs):
""" send a named parametrized command to the other side. """
self.log("sending command %s(**%s)" % (name, kwargs))
self.channel.send((name, kwargs)) | python | def sendcommand(self, name, **kwargs):
self.log("sending command %s(**%s)" % (name, kwargs))
self.channel.send((name, kwargs)) | [
"def",
"sendcommand",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"log",
"(",
"\"sending command %s(**%s)\"",
"%",
"(",
"name",
",",
"kwargs",
")",
")",
"self",
".",
"channel",
".",
"send",
"(",
"(",
"name",
",",
"kwargs... | send a named parametrized command to the other side. | [
"send",
"a",
"named",
"parametrized",
"command",
"to",
"the",
"other",
"side",
"."
] | 9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4 | https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/workermanage.py#L284-L287 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.