repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
AlecAivazis/graphql-over-kafka | nautilus/services/service.py | Service.run | def run(self, host="localhost", port=8000, shutdown_timeout=60.0, **kwargs):
"""
This function starts the service's network intefaces.
Args:
port (int): The port for the http server.
"""
print("Running service on http://localhost:%i. " % port + \
... | python | def run(self, host="localhost", port=8000, shutdown_timeout=60.0, **kwargs):
"""
This function starts the service's network intefaces.
Args:
port (int): The port for the http server.
"""
print("Running service on http://localhost:%i. " % port + \
... | [
"def",
"run",
"(",
"self",
",",
"host",
"=",
"\"localhost\"",
",",
"port",
"=",
"8000",
",",
"shutdown_timeout",
"=",
"60.0",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
"(",
"\"Running service on http://localhost:%i. \"",
"%",
"port",
"+",
"\"Press Ctrl+C to ... | This function starts the service's network intefaces.
Args:
port (int): The port for the http server. | [
"This",
"function",
"starts",
"the",
"service",
"s",
"network",
"intefaces",
"."
] | train | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/services/service.py#L208-L257 |
AlecAivazis/graphql-over-kafka | nautilus/services/service.py | Service.cleanup | def cleanup(self):
"""
This function is called when the service has finished running
regardless of intentionally or not.
"""
# if an event broker has been created for this service
if self.event_broker:
# stop the event broker
self.event_br... | python | def cleanup(self):
"""
This function is called when the service has finished running
regardless of intentionally or not.
"""
# if an event broker has been created for this service
if self.event_broker:
# stop the event broker
self.event_br... | [
"def",
"cleanup",
"(",
"self",
")",
":",
"# if an event broker has been created for this service",
"if",
"self",
".",
"event_broker",
":",
"# stop the event broker",
"self",
".",
"event_broker",
".",
"stop",
"(",
")",
"# attempt",
"try",
":",
"# close the http server",
... | This function is called when the service has finished running
regardless of intentionally or not. | [
"This",
"function",
"is",
"called",
"when",
"the",
"service",
"has",
"finished",
"running",
"regardless",
"of",
"intentionally",
"or",
"not",
"."
] | train | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/services/service.py#L260-L284 |
AlecAivazis/graphql-over-kafka | nautilus/services/service.py | Service.add_http_endpoint | def add_http_endpoint(self, url, request_handler):
"""
This method provides a programatic way of added invidual routes
to the http server.
Args:
url (str): the url to be handled by the request_handler
request_handler (nautilus.network.RequestH... | python | def add_http_endpoint(self, url, request_handler):
"""
This method provides a programatic way of added invidual routes
to the http server.
Args:
url (str): the url to be handled by the request_handler
request_handler (nautilus.network.RequestH... | [
"def",
"add_http_endpoint",
"(",
"self",
",",
"url",
",",
"request_handler",
")",
":",
"self",
".",
"app",
".",
"router",
".",
"add_route",
"(",
"'*'",
",",
"url",
",",
"request_handler",
")"
] | This method provides a programatic way of added invidual routes
to the http server.
Args:
url (str): the url to be handled by the request_handler
request_handler (nautilus.network.RequestHandler): The request handler | [
"This",
"method",
"provides",
"a",
"programatic",
"way",
"of",
"added",
"invidual",
"routes",
"to",
"the",
"http",
"server",
"."
] | train | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/services/service.py#L287-L296 |
AlecAivazis/graphql-over-kafka | nautilus/services/service.py | Service.route | def route(cls, route, config=None):
"""
This method provides a decorator for adding endpoints to the
http server.
Args:
route (str): The url to be handled by the RequestHandled
config (dict): Configuration for the request handler
... | python | def route(cls, route, config=None):
"""
This method provides a decorator for adding endpoints to the
http server.
Args:
route (str): The url to be handled by the RequestHandled
config (dict): Configuration for the request handler
... | [
"def",
"route",
"(",
"cls",
",",
"route",
",",
"config",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"wrapped_class",
",",
"*",
"*",
"kwds",
")",
":",
"# add the endpoint at the given route",
"cls",
".",
"_routes",
".",
"append",
"(",
"dict",
"(",
"u... | This method provides a decorator for adding endpoints to the
http server.
Args:
route (str): The url to be handled by the RequestHandled
config (dict): Configuration for the request handler
Example:
.. code-block:: python
... | [
"This",
"method",
"provides",
"a",
"decorator",
"for",
"adding",
"endpoints",
"to",
"the",
"http",
"server",
"."
] | train | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/services/service.py#L300-L334 |
AlecAivazis/graphql-over-kafka | nautilus/auth/util/generate_session_token.py | generate_session_token | def generate_session_token(secret_key, **payload):
"""
This function generates a session token signed by the secret key which
can be used to extract the user credentials in a verifiable way.
"""
return jwt.encode(payload, secret_key, algorithm=token_encryption_algorithm()).decode('utf-8') | python | def generate_session_token(secret_key, **payload):
"""
This function generates a session token signed by the secret key which
can be used to extract the user credentials in a verifiable way.
"""
return jwt.encode(payload, secret_key, algorithm=token_encryption_algorithm()).decode('utf-8') | [
"def",
"generate_session_token",
"(",
"secret_key",
",",
"*",
"*",
"payload",
")",
":",
"return",
"jwt",
".",
"encode",
"(",
"payload",
",",
"secret_key",
",",
"algorithm",
"=",
"token_encryption_algorithm",
"(",
")",
")",
".",
"decode",
"(",
"'utf-8'",
")"
... | This function generates a session token signed by the secret key which
can be used to extract the user credentials in a verifiable way. | [
"This",
"function",
"generates",
"a",
"session",
"token",
"signed",
"by",
"the",
"secret",
"key",
"which",
"can",
"be",
"used",
"to",
"extract",
"the",
"user",
"credentials",
"in",
"a",
"verifiable",
"way",
"."
] | train | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/auth/util/generate_session_token.py#L6-L11 |
AlecAivazis/graphql-over-kafka | nautilus/api/util/summarize_mutation.py | summarize_mutation | def summarize_mutation(mutation_name, event, inputs, outputs, isAsync=False):
"""
This function provides a standard representation of mutations to be
used when services announce themselves
"""
return dict(
name=mutation_name,
event=event,
isAsync=isAsync,
inpu... | python | def summarize_mutation(mutation_name, event, inputs, outputs, isAsync=False):
"""
This function provides a standard representation of mutations to be
used when services announce themselves
"""
return dict(
name=mutation_name,
event=event,
isAsync=isAsync,
inpu... | [
"def",
"summarize_mutation",
"(",
"mutation_name",
",",
"event",
",",
"inputs",
",",
"outputs",
",",
"isAsync",
"=",
"False",
")",
":",
"return",
"dict",
"(",
"name",
"=",
"mutation_name",
",",
"event",
"=",
"event",
",",
"isAsync",
"=",
"isAsync",
",",
... | This function provides a standard representation of mutations to be
used when services announce themselves | [
"This",
"function",
"provides",
"a",
"standard",
"representation",
"of",
"mutations",
"to",
"be",
"used",
"when",
"services",
"announce",
"themselves"
] | train | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/api/util/summarize_mutation.py#L1-L12 |
AlecAivazis/graphql-over-kafka | nautilus/auth/primitives/passwordHash.py | PasswordHash.new | def new(cls, password, rounds):
"""Creates a PasswordHash from the given password."""
if isinstance(password, str):
password = password.encode('utf-8')
return cls(cls._new(password, rounds)) | python | def new(cls, password, rounds):
"""Creates a PasswordHash from the given password."""
if isinstance(password, str):
password = password.encode('utf-8')
return cls(cls._new(password, rounds)) | [
"def",
"new",
"(",
"cls",
",",
"password",
",",
"rounds",
")",
":",
"if",
"isinstance",
"(",
"password",
",",
"str",
")",
":",
"password",
"=",
"password",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"cls",
"(",
"cls",
".",
"_new",
"(",
"password",... | Creates a PasswordHash from the given password. | [
"Creates",
"a",
"PasswordHash",
"from",
"the",
"given",
"password",
"."
] | train | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/auth/primitives/passwordHash.py#L51-L55 |
AlecAivazis/graphql-over-kafka | nautilus/auth/primitives/passwordHash.py | PasswordHash.coerce | def coerce(cls, key, value):
"""Ensure that loaded values are PasswordHashes."""
if isinstance(value, PasswordHash):
return value
return super(PasswordHash, cls).coerce(key, value) | python | def coerce(cls, key, value):
"""Ensure that loaded values are PasswordHashes."""
if isinstance(value, PasswordHash):
return value
return super(PasswordHash, cls).coerce(key, value) | [
"def",
"coerce",
"(",
"cls",
",",
"key",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"PasswordHash",
")",
":",
"return",
"value",
"return",
"super",
"(",
"PasswordHash",
",",
"cls",
")",
".",
"coerce",
"(",
"key",
",",
"value",
")"... | Ensure that loaded values are PasswordHashes. | [
"Ensure",
"that",
"loaded",
"values",
"are",
"PasswordHashes",
"."
] | train | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/auth/primitives/passwordHash.py#L59-L63 |
AlecAivazis/graphql-over-kafka | nautilus/auth/primitives/passwordHash.py | PasswordHash.rehash | def rehash(self, password):
"""Recreates the internal hash."""
self.hash = self._new(password, self.desired_rounds)
self.rounds = self.desired_rounds | python | def rehash(self, password):
"""Recreates the internal hash."""
self.hash = self._new(password, self.desired_rounds)
self.rounds = self.desired_rounds | [
"def",
"rehash",
"(",
"self",
",",
"password",
")",
":",
"self",
".",
"hash",
"=",
"self",
".",
"_new",
"(",
"password",
",",
"self",
".",
"desired_rounds",
")",
"self",
".",
"rounds",
"=",
"self",
".",
"desired_rounds"
] | Recreates the internal hash. | [
"Recreates",
"the",
"internal",
"hash",
"."
] | train | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/auth/primitives/passwordHash.py#L75-L78 |
AlecAivazis/graphql-over-kafka | nautilus/services/modelService.py | ModelService.init_db | def init_db(self):
"""
This function configures the database used for models to make
the configuration parameters.
"""
# get the database url from the configuration
db_url = self.config.get('database_url', 'sqlite:///nautilus.db')
# configure the nautilus ... | python | def init_db(self):
"""
This function configures the database used for models to make
the configuration parameters.
"""
# get the database url from the configuration
db_url = self.config.get('database_url', 'sqlite:///nautilus.db')
# configure the nautilus ... | [
"def",
"init_db",
"(",
"self",
")",
":",
"# get the database url from the configuration",
"db_url",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'database_url'",
",",
"'sqlite:///nautilus.db'",
")",
"# configure the nautilus database to the url",
"nautilus",
".",
"databa... | This function configures the database used for models to make
the configuration parameters. | [
"This",
"function",
"configures",
"the",
"database",
"used",
"for",
"models",
"to",
"make",
"the",
"configuration",
"parameters",
"."
] | train | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/services/modelService.py#L101-L109 |
AlecAivazis/graphql-over-kafka | nautilus/services/apiGateway.py | APIGateway.auth_criteria | def auth_criteria(self):
"""
This attribute provides the mapping of services to their auth requirement
Returns:
(dict) : the mapping from services to their auth requirements.
"""
# the dictionary we will return
auth = {}
# go over each at... | python | def auth_criteria(self):
"""
This attribute provides the mapping of services to their auth requirement
Returns:
(dict) : the mapping from services to their auth requirements.
"""
# the dictionary we will return
auth = {}
# go over each at... | [
"def",
"auth_criteria",
"(",
"self",
")",
":",
"# the dictionary we will return",
"auth",
"=",
"{",
"}",
"# go over each attribute of the service",
"for",
"attr",
"in",
"dir",
"(",
"self",
")",
":",
"# make sure we could hit an infinite loop",
"if",
"attr",
"!=",
"'au... | This attribute provides the mapping of services to their auth requirement
Returns:
(dict) : the mapping from services to their auth requirements. | [
"This",
"attribute",
"provides",
"the",
"mapping",
"of",
"services",
"to",
"their",
"auth",
"requirement"
] | train | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/services/apiGateway.py#L87-L109 |
AlecAivazis/graphql-over-kafka | nautilus/services/apiGateway.py | APIGateway.login_user | async def login_user(self, password, **kwds):
"""
This function handles the registration of the given user credentials in the database
"""
# find the matching user with the given email
user_data = (await self._get_matching_user(fields=list(kwds.keys()), **kwds))['data']
... | python | async def login_user(self, password, **kwds):
"""
This function handles the registration of the given user credentials in the database
"""
# find the matching user with the given email
user_data = (await self._get_matching_user(fields=list(kwds.keys()), **kwds))['data']
... | [
"async",
"def",
"login_user",
"(",
"self",
",",
"password",
",",
"*",
"*",
"kwds",
")",
":",
"# find the matching user with the given email",
"user_data",
"=",
"(",
"await",
"self",
".",
"_get_matching_user",
"(",
"fields",
"=",
"list",
"(",
"kwds",
".",
"keys... | This function handles the registration of the given user credentials in the database | [
"This",
"function",
"handles",
"the",
"registration",
"of",
"the",
"given",
"user",
"credentials",
"in",
"the",
"database"
] | train | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/services/apiGateway.py#L144-L172 |
AlecAivazis/graphql-over-kafka | nautilus/services/apiGateway.py | APIGateway.register_user | async def register_user(self, password, **kwds):
"""
This function is used to provide a sessionToken for later requests.
Args:
uid (str): The
"""
# so make one
user = await self._create_remote_user(password=password, **kwds)
# if there is ... | python | async def register_user(self, password, **kwds):
"""
This function is used to provide a sessionToken for later requests.
Args:
uid (str): The
"""
# so make one
user = await self._create_remote_user(password=password, **kwds)
# if there is ... | [
"async",
"def",
"register_user",
"(",
"self",
",",
"password",
",",
"*",
"*",
"kwds",
")",
":",
"# so make one",
"user",
"=",
"await",
"self",
".",
"_create_remote_user",
"(",
"password",
"=",
"password",
",",
"*",
"*",
"kwds",
")",
"# if there is no pk fiel... | This function is used to provide a sessionToken for later requests.
Args:
uid (str): The | [
"This",
"function",
"is",
"used",
"to",
"provide",
"a",
"sessionToken",
"for",
"later",
"requests",
"."
] | train | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/services/apiGateway.py#L175-L207 |
AlecAivazis/graphql-over-kafka | nautilus/services/apiGateway.py | APIGateway.object_resolver | async def object_resolver(self, object_name, fields, obey_auth=False, current_user=None, **filters):
"""
This function resolves a given object in the remote backend services
"""
try:
# check if an object with that name has been registered
registered = [model ... | python | async def object_resolver(self, object_name, fields, obey_auth=False, current_user=None, **filters):
"""
This function resolves a given object in the remote backend services
"""
try:
# check if an object with that name has been registered
registered = [model ... | [
"async",
"def",
"object_resolver",
"(",
"self",
",",
"object_name",
",",
"fields",
",",
"obey_auth",
"=",
"False",
",",
"current_user",
"=",
"None",
",",
"*",
"*",
"filters",
")",
":",
"try",
":",
"# check if an object with that name has been registered",
"registe... | This function resolves a given object in the remote backend services | [
"This",
"function",
"resolves",
"a",
"given",
"object",
"in",
"the",
"remote",
"backend",
"services"
] | train | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/services/apiGateway.py#L210-L293 |
AlecAivazis/graphql-over-kafka | nautilus/services/apiGateway.py | APIGateway.mutation_resolver | async def mutation_resolver(self, mutation_name, args, fields):
"""
the default behavior for mutations is to look up the event,
publish the correct event type with the args as the body,
and return the fields contained in the result
"""
try:
# make... | python | async def mutation_resolver(self, mutation_name, args, fields):
"""
the default behavior for mutations is to look up the event,
publish the correct event type with the args as the body,
and return the fields contained in the result
"""
try:
# make... | [
"async",
"def",
"mutation_resolver",
"(",
"self",
",",
"mutation_name",
",",
"args",
",",
"fields",
")",
":",
"try",
":",
"# make sure we can identify the mutation",
"mutation_summary",
"=",
"[",
"mutation",
"for",
"mutation",
"in",
"self",
".",
"_external_service_d... | the default behavior for mutations is to look up the event,
publish the correct event type with the args as the body,
and return the fields contained in the result | [
"the",
"default",
"behavior",
"for",
"mutations",
"is",
"to",
"look",
"up",
"the",
"event",
"publish",
"the",
"correct",
"event",
"type",
"with",
"the",
"args",
"as",
"the",
"body",
"and",
"return",
"the",
"fields",
"contained",
"in",
"the",
"result"
] | train | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/services/apiGateway.py#L350-L385 |
AlecAivazis/graphql-over-kafka | nautilus/services/apiGateway.py | APIGateway._check_for_matching_user | async def _check_for_matching_user(self, **user_filters):
"""
This function checks if there is a user with the same uid in the
remote user service
Args:
**kwds : the filters of the user to check for
Returns:
(bool): wether or not th... | python | async def _check_for_matching_user(self, **user_filters):
"""
This function checks if there is a user with the same uid in the
remote user service
Args:
**kwds : the filters of the user to check for
Returns:
(bool): wether or not th... | [
"async",
"def",
"_check_for_matching_user",
"(",
"self",
",",
"*",
"*",
"user_filters",
")",
":",
"# there is a matching user if there are no errors and no results from",
"user_data",
"=",
"self",
".",
"_get_matching_user",
"(",
"user_filters",
")",
"# return true if there we... | This function checks if there is a user with the same uid in the
remote user service
Args:
**kwds : the filters of the user to check for
Returns:
(bool): wether or not there is a matching user | [
"This",
"function",
"checks",
"if",
"there",
"is",
"a",
"user",
"with",
"the",
"same",
"uid",
"in",
"the",
"remote",
"user",
"service",
"Args",
":",
"**",
"kwds",
":",
"the",
"filters",
"of",
"the",
"user",
"to",
"check",
"for",
"Returns",
":",
"(",
... | train | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/services/apiGateway.py#L434-L447 |
AlecAivazis/graphql-over-kafka | nautilus/services/apiGateway.py | APIGateway._create_remote_user | async def _create_remote_user(self, **payload):
"""
This method creates a service record in the remote user service
with the given email.
Args:
uid (str): the user identifier to create
Returns:
(dict): a summary of the user that was... | python | async def _create_remote_user(self, **payload):
"""
This method creates a service record in the remote user service
with the given email.
Args:
uid (str): the user identifier to create
Returns:
(dict): a summary of the user that was... | [
"async",
"def",
"_create_remote_user",
"(",
"self",
",",
"*",
"*",
"payload",
")",
":",
"# the action for reading user entries",
"read_action",
"=",
"get_crud_action",
"(",
"method",
"=",
"'create'",
",",
"model",
"=",
"'user'",
")",
"# see if there is a matching user... | This method creates a service record in the remote user service
with the given email.
Args:
uid (str): the user identifier to create
Returns:
(dict): a summary of the user that was created | [
"This",
"method",
"creates",
"a",
"service",
"record",
"in",
"the",
"remote",
"user",
"service",
"with",
"the",
"given",
"email",
".",
"Args",
":",
"uid",
"(",
"str",
")",
":",
"the",
"user",
"identifier",
"to",
"create",
"Returns",
":",
"(",
"dict",
"... | train | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/services/apiGateway.py#L450-L468 |
MartinThoma/asr | asr/align.py | calculate_wer | def calculate_wer(reference, hypothesis):
"""
Calculation of WER with Levenshtein distance.
Works only for iterables up to 254 elements (uint8).
O(nm) time and space complexity.
>>> calculate_wer("who is there".split(), "is there".split())
1
>>> calculate_wer("who is... | python | def calculate_wer(reference, hypothesis):
"""
Calculation of WER with Levenshtein distance.
Works only for iterables up to 254 elements (uint8).
O(nm) time and space complexity.
>>> calculate_wer("who is there".split(), "is there".split())
1
>>> calculate_wer("who is... | [
"def",
"calculate_wer",
"(",
"reference",
",",
"hypothesis",
")",
":",
"# initialisation",
"import",
"numpy",
"d",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"len",
"(",
"reference",
")",
"+",
"1",
")",
"*",
"(",
"len",
"(",
"hypothesis",
")",
"+",
"1",
"... | Calculation of WER with Levenshtein distance.
Works only for iterables up to 254 elements (uint8).
O(nm) time and space complexity.
>>> calculate_wer("who is there".split(), "is there".split())
1
>>> calculate_wer("who is there".split(), "".split())
3
>>> calcula... | [
"Calculation",
"of",
"WER",
"with",
"Levenshtein",
"distance",
".",
"Works",
"only",
"for",
"iterables",
"up",
"to",
"254",
"elements",
"(",
"uint8",
")",
".",
"O",
"(",
"nm",
")",
"time",
"and",
"space",
"complexity",
"."
] | train | https://github.com/MartinThoma/asr/blob/b453074761a4a2f1ee40cd5315b2e000c3b72142/asr/align.py#L7-L42 |
MartinThoma/asr | asr/align.py | get_parser | def get_parser():
"""Get a parser object"""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument("-s1", dest="s1", help="sequence 1")
parser.add_a... | python | def get_parser():
"""Get a parser object"""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument("-s1", dest="s1", help="sequence 1")
parser.add_a... | [
"def",
"get_parser",
"(",
")",
":",
"from",
"argparse",
"import",
"ArgumentParser",
",",
"ArgumentDefaultsHelpFormatter",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
",",
"formatter_class",
"=",
"ArgumentDefaultsHelpFormatter",
")",
"parser",
... | Get a parser object | [
"Get",
"a",
"parser",
"object"
] | train | https://github.com/MartinThoma/asr/blob/b453074761a4a2f1ee40cd5315b2e000c3b72142/asr/align.py#L45-L52 |
pschmitt/pyteleloisirs | pyteleloisirs/pyteleloisirs.py | _async_request_soup | async def _async_request_soup(url):
'''
Perform a GET web request and return a bs4 parser
'''
from bs4 import BeautifulSoup
import aiohttp
_LOGGER.debug('GET %s', url)
async with aiohttp.ClientSession() as session:
resp = await session.get(url)
text = await resp.text()
... | python | async def _async_request_soup(url):
'''
Perform a GET web request and return a bs4 parser
'''
from bs4 import BeautifulSoup
import aiohttp
_LOGGER.debug('GET %s', url)
async with aiohttp.ClientSession() as session:
resp = await session.get(url)
text = await resp.text()
... | [
"async",
"def",
"_async_request_soup",
"(",
"url",
")",
":",
"from",
"bs4",
"import",
"BeautifulSoup",
"import",
"aiohttp",
"_LOGGER",
".",
"debug",
"(",
"'GET %s'",
",",
"url",
")",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"session"... | Perform a GET web request and return a bs4 parser | [
"Perform",
"a",
"GET",
"web",
"request",
"and",
"return",
"a",
"bs4",
"parser"
] | train | https://github.com/pschmitt/pyteleloisirs/blob/d63610fd3729862455ac42afca440469f8063fba/pyteleloisirs/pyteleloisirs.py#L15-L25 |
pschmitt/pyteleloisirs | pyteleloisirs/pyteleloisirs.py | async_determine_channel | async def async_determine_channel(channel):
'''
Check whether the current channel is correct. If not try to determine it
using fuzzywuzzy
'''
from fuzzywuzzy import process
channel_data = await async_get_channels()
if not channel_data:
_LOGGER.error('No channel data. Cannot determine... | python | async def async_determine_channel(channel):
'''
Check whether the current channel is correct. If not try to determine it
using fuzzywuzzy
'''
from fuzzywuzzy import process
channel_data = await async_get_channels()
if not channel_data:
_LOGGER.error('No channel data. Cannot determine... | [
"async",
"def",
"async_determine_channel",
"(",
"channel",
")",
":",
"from",
"fuzzywuzzy",
"import",
"process",
"channel_data",
"=",
"await",
"async_get_channels",
"(",
")",
"if",
"not",
"channel_data",
":",
"_LOGGER",
".",
"error",
"(",
"'No channel data. Cannot de... | Check whether the current channel is correct. If not try to determine it
using fuzzywuzzy | [
"Check",
"whether",
"the",
"current",
"channel",
"is",
"correct",
".",
"If",
"not",
"try",
"to",
"determine",
"it",
"using",
"fuzzywuzzy"
] | train | https://github.com/pschmitt/pyteleloisirs/blob/d63610fd3729862455ac42afca440469f8063fba/pyteleloisirs/pyteleloisirs.py#L28-L45 |
pschmitt/pyteleloisirs | pyteleloisirs/pyteleloisirs.py | async_get_channels | async def async_get_channels(no_cache=False, refresh_interval=4):
'''
Get channel list and corresponding urls
'''
# Check cache
now = datetime.datetime.now()
max_cache_age = datetime.timedelta(hours=refresh_interval)
if not no_cache and 'channels' in _CACHE:
cache = _CACHE.get('chann... | python | async def async_get_channels(no_cache=False, refresh_interval=4):
'''
Get channel list and corresponding urls
'''
# Check cache
now = datetime.datetime.now()
max_cache_age = datetime.timedelta(hours=refresh_interval)
if not no_cache and 'channels' in _CACHE:
cache = _CACHE.get('chann... | [
"async",
"def",
"async_get_channels",
"(",
"no_cache",
"=",
"False",
",",
"refresh_interval",
"=",
"4",
")",
":",
"# Check cache",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"max_cache_age",
"=",
"datetime",
".",
"timedelta",
"(",
"hours"... | Get channel list and corresponding urls | [
"Get",
"channel",
"list",
"and",
"corresponding",
"urls"
] | train | https://github.com/pschmitt/pyteleloisirs/blob/d63610fd3729862455ac42afca440469f8063fba/pyteleloisirs/pyteleloisirs.py#L48-L80 |
pschmitt/pyteleloisirs | pyteleloisirs/pyteleloisirs.py | resize_program_image | def resize_program_image(img_url, img_size=300):
'''
Resize a program's thumbnail to the desired dimension
'''
match = re.match(r'.+/(\d+)x(\d+)/.+', img_url)
if not match:
_LOGGER.warning('Could not compute current image resolution of %s',
img_url)
return img... | python | def resize_program_image(img_url, img_size=300):
'''
Resize a program's thumbnail to the desired dimension
'''
match = re.match(r'.+/(\d+)x(\d+)/.+', img_url)
if not match:
_LOGGER.warning('Could not compute current image resolution of %s',
img_url)
return img... | [
"def",
"resize_program_image",
"(",
"img_url",
",",
"img_size",
"=",
"300",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r'.+/(\\d+)x(\\d+)/.+'",
",",
"img_url",
")",
"if",
"not",
"match",
":",
"_LOGGER",
".",
"warning",
"(",
"'Could not compute current i... | Resize a program's thumbnail to the desired dimension | [
"Resize",
"a",
"program",
"s",
"thumbnail",
"to",
"the",
"desired",
"dimension"
] | train | https://github.com/pschmitt/pyteleloisirs/blob/d63610fd3729862455ac42afca440469f8063fba/pyteleloisirs/pyteleloisirs.py#L83-L99 |
pschmitt/pyteleloisirs | pyteleloisirs/pyteleloisirs.py | get_current_program_progress | def get_current_program_progress(program):
'''
Get the current progress of the program in %
'''
now = datetime.datetime.now()
program_duration = get_program_duration(program)
if not program_duration:
return
progress = now - program.get('start_time')
return progress.seconds * 100 ... | python | def get_current_program_progress(program):
'''
Get the current progress of the program in %
'''
now = datetime.datetime.now()
program_duration = get_program_duration(program)
if not program_duration:
return
progress = now - program.get('start_time')
return progress.seconds * 100 ... | [
"def",
"get_current_program_progress",
"(",
"program",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"program_duration",
"=",
"get_program_duration",
"(",
"program",
")",
"if",
"not",
"program_duration",
":",
"return",
"progress",
"=",... | Get the current progress of the program in % | [
"Get",
"the",
"current",
"progress",
"of",
"the",
"program",
"in",
"%"
] | train | https://github.com/pschmitt/pyteleloisirs/blob/d63610fd3729862455ac42afca440469f8063fba/pyteleloisirs/pyteleloisirs.py#L102-L111 |
pschmitt/pyteleloisirs | pyteleloisirs/pyteleloisirs.py | get_program_duration | def get_program_duration(program):
'''
Get a program's duration in seconds
'''
program_start = program.get('start_time')
program_end = program.get('end_time')
if not program_start or not program_end:
_LOGGER.error('Could not determine program start and/or end times.')
_LOGGER.deb... | python | def get_program_duration(program):
'''
Get a program's duration in seconds
'''
program_start = program.get('start_time')
program_end = program.get('end_time')
if not program_start or not program_end:
_LOGGER.error('Could not determine program start and/or end times.')
_LOGGER.deb... | [
"def",
"get_program_duration",
"(",
"program",
")",
":",
"program_start",
"=",
"program",
".",
"get",
"(",
"'start_time'",
")",
"program_end",
"=",
"program",
".",
"get",
"(",
"'end_time'",
")",
"if",
"not",
"program_start",
"or",
"not",
"program_end",
":",
... | Get a program's duration in seconds | [
"Get",
"a",
"program",
"s",
"duration",
"in",
"seconds"
] | train | https://github.com/pschmitt/pyteleloisirs/blob/d63610fd3729862455ac42afca440469f8063fba/pyteleloisirs/pyteleloisirs.py#L114-L125 |
pschmitt/pyteleloisirs | pyteleloisirs/pyteleloisirs.py | get_remaining_time | def get_remaining_time(program):
'''
Get the remaining time in seconds of a program that is currently on.
'''
now = datetime.datetime.now()
program_start = program.get('start_time')
program_end = program.get('end_time')
if not program_start or not program_end:
_LOGGER.error('Could no... | python | def get_remaining_time(program):
'''
Get the remaining time in seconds of a program that is currently on.
'''
now = datetime.datetime.now()
program_start = program.get('start_time')
program_end = program.get('end_time')
if not program_start or not program_end:
_LOGGER.error('Could no... | [
"def",
"get_remaining_time",
"(",
"program",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"program_start",
"=",
"program",
".",
"get",
"(",
"'start_time'",
")",
"program_end",
"=",
"program",
".",
"get",
"(",
"'end_time'",
")",
... | Get the remaining time in seconds of a program that is currently on. | [
"Get",
"the",
"remaining",
"time",
"in",
"seconds",
"of",
"a",
"program",
"that",
"is",
"currently",
"on",
"."
] | train | https://github.com/pschmitt/pyteleloisirs/blob/d63610fd3729862455ac42afca440469f8063fba/pyteleloisirs/pyteleloisirs.py#L128-L144 |
pschmitt/pyteleloisirs | pyteleloisirs/pyteleloisirs.py | extract_program_summary | def extract_program_summary(data):
'''
Extract the summary data from a program's detail page
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(data, 'html.parser')
try:
return soup.find(
'div', {'class': 'episode-synopsis'}
).find_all('div')[-1].text.strip()
... | python | def extract_program_summary(data):
'''
Extract the summary data from a program's detail page
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(data, 'html.parser')
try:
return soup.find(
'div', {'class': 'episode-synopsis'}
).find_all('div')[-1].text.strip()
... | [
"def",
"extract_program_summary",
"(",
"data",
")",
":",
"from",
"bs4",
"import",
"BeautifulSoup",
"soup",
"=",
"BeautifulSoup",
"(",
"data",
",",
"'html.parser'",
")",
"try",
":",
"return",
"soup",
".",
"find",
"(",
"'div'",
",",
"{",
"'class'",
":",
"'ep... | Extract the summary data from a program's detail page | [
"Extract",
"the",
"summary",
"data",
"from",
"a",
"program",
"s",
"detail",
"page"
] | train | https://github.com/pschmitt/pyteleloisirs/blob/d63610fd3729862455ac42afca440469f8063fba/pyteleloisirs/pyteleloisirs.py#L147-L160 |
pschmitt/pyteleloisirs | pyteleloisirs/pyteleloisirs.py | async_set_summary | async def async_set_summary(program):
'''
Set a program's summary
'''
import aiohttp
async with aiohttp.ClientSession() as session:
resp = await session.get(program.get('url'))
text = await resp.text()
summary = extract_program_summary(text)
program['summary'] = summa... | python | async def async_set_summary(program):
'''
Set a program's summary
'''
import aiohttp
async with aiohttp.ClientSession() as session:
resp = await session.get(program.get('url'))
text = await resp.text()
summary = extract_program_summary(text)
program['summary'] = summa... | [
"async",
"def",
"async_set_summary",
"(",
"program",
")",
":",
"import",
"aiohttp",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"session",
":",
"resp",
"=",
"await",
"session",
".",
"get",
"(",
"program",
".",
"get",
"(",
"'url'",
"... | Set a program's summary | [
"Set",
"a",
"program",
"s",
"summary"
] | train | https://github.com/pschmitt/pyteleloisirs/blob/d63610fd3729862455ac42afca440469f8063fba/pyteleloisirs/pyteleloisirs.py#L163-L173 |
pschmitt/pyteleloisirs | pyteleloisirs/pyteleloisirs.py | async_get_program_guide | async def async_get_program_guide(channel, no_cache=False, refresh_interval=4):
'''
Get the program data for a channel
'''
chan = await async_determine_channel(channel)
now = datetime.datetime.now()
max_cache_age = datetime.timedelta(hours=refresh_interval)
if not no_cache and 'guide' in _CA... | python | async def async_get_program_guide(channel, no_cache=False, refresh_interval=4):
'''
Get the program data for a channel
'''
chan = await async_determine_channel(channel)
now = datetime.datetime.now()
max_cache_age = datetime.timedelta(hours=refresh_interval)
if not no_cache and 'guide' in _CA... | [
"async",
"def",
"async_get_program_guide",
"(",
"channel",
",",
"no_cache",
"=",
"False",
",",
"refresh_interval",
"=",
"4",
")",
":",
"chan",
"=",
"await",
"async_determine_channel",
"(",
"channel",
")",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
... | Get the program data for a channel | [
"Get",
"the",
"program",
"data",
"for",
"a",
"channel"
] | train | https://github.com/pschmitt/pyteleloisirs/blob/d63610fd3729862455ac42afca440469f8063fba/pyteleloisirs/pyteleloisirs.py#L176-L232 |
pschmitt/pyteleloisirs | pyteleloisirs/pyteleloisirs.py | async_get_current_program | async def async_get_current_program(channel, no_cache=False):
'''
Get the current program info
'''
chan = await async_determine_channel(channel)
guide = await async_get_program_guide(chan, no_cache)
if not guide:
_LOGGER.warning('Could not retrieve TV program for %s', channel)
re... | python | async def async_get_current_program(channel, no_cache=False):
'''
Get the current program info
'''
chan = await async_determine_channel(channel)
guide = await async_get_program_guide(chan, no_cache)
if not guide:
_LOGGER.warning('Could not retrieve TV program for %s', channel)
re... | [
"async",
"def",
"async_get_current_program",
"(",
"channel",
",",
"no_cache",
"=",
"False",
")",
":",
"chan",
"=",
"await",
"async_determine_channel",
"(",
"channel",
")",
"guide",
"=",
"await",
"async_get_program_guide",
"(",
"chan",
",",
"no_cache",
")",
"if",... | Get the current program info | [
"Get",
"the",
"current",
"program",
"info"
] | train | https://github.com/pschmitt/pyteleloisirs/blob/d63610fd3729862455ac42afca440469f8063fba/pyteleloisirs/pyteleloisirs.py#L235-L249 |
tcpcloud/python-aptly | aptly/publisher/__init__.py | PublishManager.publish | def publish(self, distribution, storage=""):
"""
Get or create publish
"""
try:
return self._publishes[distribution]
except KeyError:
self._publishes[distribution] = Publish(self.client, distribution, timestamp=self.timestamp, storage=(storage or self.stor... | python | def publish(self, distribution, storage=""):
"""
Get or create publish
"""
try:
return self._publishes[distribution]
except KeyError:
self._publishes[distribution] = Publish(self.client, distribution, timestamp=self.timestamp, storage=(storage or self.stor... | [
"def",
"publish",
"(",
"self",
",",
"distribution",
",",
"storage",
"=",
"\"\"",
")",
":",
"try",
":",
"return",
"self",
".",
"_publishes",
"[",
"distribution",
"]",
"except",
"KeyError",
":",
"self",
".",
"_publishes",
"[",
"distribution",
"]",
"=",
"Pu... | Get or create publish | [
"Get",
"or",
"create",
"publish"
] | train | https://github.com/tcpcloud/python-aptly/blob/7eb4ce1c508666bad0e6a0d4c5c561b1485ed558/aptly/publisher/__init__.py#L29-L37 |
tcpcloud/python-aptly | aptly/publisher/__init__.py | PublishManager.add | def add(self, snapshot, distributions, component='main', storage=""):
""" Add mirror or repo to publish """
for dist in distributions:
self.publish(dist, storage=storage).add(snapshot, component) | python | def add(self, snapshot, distributions, component='main', storage=""):
""" Add mirror or repo to publish """
for dist in distributions:
self.publish(dist, storage=storage).add(snapshot, component) | [
"def",
"add",
"(",
"self",
",",
"snapshot",
",",
"distributions",
",",
"component",
"=",
"'main'",
",",
"storage",
"=",
"\"\"",
")",
":",
"for",
"dist",
"in",
"distributions",
":",
"self",
".",
"publish",
"(",
"dist",
",",
"storage",
"=",
"storage",
")... | Add mirror or repo to publish | [
"Add",
"mirror",
"or",
"repo",
"to",
"publish"
] | train | https://github.com/tcpcloud/python-aptly/blob/7eb4ce1c508666bad0e6a0d4c5c561b1485ed558/aptly/publisher/__init__.py#L39-L42 |
tcpcloud/python-aptly | aptly/publisher/__init__.py | PublishManager._publish_match | def _publish_match(self, publish, names=False, name_only=False):
"""
Check if publish name matches list of names or regex patterns
"""
if names:
for name in names:
if not name_only and isinstance(name, re._pattern_type):
if re.match(name, p... | python | def _publish_match(self, publish, names=False, name_only=False):
"""
Check if publish name matches list of names or regex patterns
"""
if names:
for name in names:
if not name_only and isinstance(name, re._pattern_type):
if re.match(name, p... | [
"def",
"_publish_match",
"(",
"self",
",",
"publish",
",",
"names",
"=",
"False",
",",
"name_only",
"=",
"False",
")",
":",
"if",
"names",
":",
"for",
"name",
"in",
"names",
":",
"if",
"not",
"name_only",
"and",
"isinstance",
"(",
"name",
",",
"re",
... | Check if publish name matches list of names or regex patterns | [
"Check",
"if",
"publish",
"name",
"matches",
"list",
"of",
"names",
"or",
"regex",
"patterns"
] | train | https://github.com/tcpcloud/python-aptly/blob/7eb4ce1c508666bad0e6a0d4c5c561b1485ed558/aptly/publisher/__init__.py#L87-L102 |
tcpcloud/python-aptly | aptly/publisher/__init__.py | PublishManager.get_repo_information | def get_repo_information(config, client, fill_repo=False, components=[]):
""" fill two dictionnaries : one containing all the packages for every repository
and the second one associating to every component of every publish its repository"""
repo_dict = {}
publish_dict = {}
f... | python | def get_repo_information(config, client, fill_repo=False, components=[]):
""" fill two dictionnaries : one containing all the packages for every repository
and the second one associating to every component of every publish its repository"""
repo_dict = {}
publish_dict = {}
f... | [
"def",
"get_repo_information",
"(",
"config",
",",
"client",
",",
"fill_repo",
"=",
"False",
",",
"components",
"=",
"[",
"]",
")",
":",
"repo_dict",
"=",
"{",
"}",
"publish_dict",
"=",
"{",
"}",
"for",
"origin",
"in",
"[",
"'repo'",
",",
"'mirror'",
"... | fill two dictionnaries : one containing all the packages for every repository
and the second one associating to every component of every publish its repository | [
"fill",
"two",
"dictionnaries",
":",
"one",
"containing",
"all",
"the",
"packages",
"for",
"every",
"repository",
"and",
"the",
"second",
"one",
"associating",
"to",
"every",
"component",
"of",
"every",
"publish",
"its",
"repository"
] | train | https://github.com/tcpcloud/python-aptly/blob/7eb4ce1c508666bad0e6a0d4c5c561b1485ed558/aptly/publisher/__init__.py#L144-L161 |
tcpcloud/python-aptly | aptly/publisher/__init__.py | Publish.compare | def compare(self, other, components=[]):
"""
Compare two publishes
It expects that other publish is same or older than this one
Return tuple (diff, equal) of dict {'component': ['snapshot']}
"""
lg.debug("Comparing publish %s (%s) and %s (%s)" % (self.name, self.storage ... | python | def compare(self, other, components=[]):
"""
Compare two publishes
It expects that other publish is same or older than this one
Return tuple (diff, equal) of dict {'component': ['snapshot']}
"""
lg.debug("Comparing publish %s (%s) and %s (%s)" % (self.name, self.storage ... | [
"def",
"compare",
"(",
"self",
",",
"other",
",",
"components",
"=",
"[",
"]",
")",
":",
"lg",
".",
"debug",
"(",
"\"Comparing publish %s (%s) and %s (%s)\"",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"storage",
"or",
"\"local\"",
",",
"other",
".... | Compare two publishes
It expects that other publish is same or older than this one
Return tuple (diff, equal) of dict {'component': ['snapshot']} | [
"Compare",
"two",
"publishes",
"It",
"expects",
"that",
"other",
"publish",
"is",
"same",
"or",
"older",
"than",
"this",
"one"
] | train | https://github.com/tcpcloud/python-aptly/blob/7eb4ce1c508666bad0e6a0d4c5c561b1485ed558/aptly/publisher/__init__.py#L275-L302 |
tcpcloud/python-aptly | aptly/publisher/__init__.py | Publish._get_publish | def _get_publish(self):
"""
Find this publish on remote
"""
publishes = self._get_publishes(self.client)
for publish in publishes:
if publish['Distribution'] == self.distribution and \
publish['Prefix'].replace("/", "_") == (self.prefix or '.') and... | python | def _get_publish(self):
"""
Find this publish on remote
"""
publishes = self._get_publishes(self.client)
for publish in publishes:
if publish['Distribution'] == self.distribution and \
publish['Prefix'].replace("/", "_") == (self.prefix or '.') and... | [
"def",
"_get_publish",
"(",
"self",
")",
":",
"publishes",
"=",
"self",
".",
"_get_publishes",
"(",
"self",
".",
"client",
")",
"for",
"publish",
"in",
"publishes",
":",
"if",
"publish",
"[",
"'Distribution'",
"]",
"==",
"self",
".",
"distribution",
"and",... | Find this publish on remote | [
"Find",
"this",
"publish",
"on",
"remote"
] | train | https://github.com/tcpcloud/python-aptly/blob/7eb4ce1c508666bad0e6a0d4c5c561b1485ed558/aptly/publisher/__init__.py#L351-L361 |
tcpcloud/python-aptly | aptly/publisher/__init__.py | Publish.save_publish | def save_publish(self, save_path):
"""
Serialize publish in YAML
"""
timestamp = time.strftime("%Y%m%d%H%M%S")
yaml_dict = {}
yaml_dict["publish"] = self.name
yaml_dict["name"] = timestamp
yaml_dict["components"] = []
yaml_dict["storage"] = self.s... | python | def save_publish(self, save_path):
"""
Serialize publish in YAML
"""
timestamp = time.strftime("%Y%m%d%H%M%S")
yaml_dict = {}
yaml_dict["publish"] = self.name
yaml_dict["name"] = timestamp
yaml_dict["components"] = []
yaml_dict["storage"] = self.s... | [
"def",
"save_publish",
"(",
"self",
",",
"save_path",
")",
":",
"timestamp",
"=",
"time",
".",
"strftime",
"(",
"\"%Y%m%d%H%M%S\"",
")",
"yaml_dict",
"=",
"{",
"}",
"yaml_dict",
"[",
"\"publish\"",
"]",
"=",
"self",
".",
"name",
"yaml_dict",
"[",
"\"name\"... | Serialize publish in YAML | [
"Serialize",
"publish",
"in",
"YAML"
] | train | https://github.com/tcpcloud/python-aptly/blob/7eb4ce1c508666bad0e6a0d4c5c561b1485ed558/aptly/publisher/__init__.py#L367-L392 |
tcpcloud/python-aptly | aptly/publisher/__init__.py | Publish.restore_publish | def restore_publish(self, config, components, recreate=False):
"""
Restore publish from config file
"""
if "all" in components:
components = []
try:
self.load()
publish = True
except NoSuchPublish:
publish = False
... | python | def restore_publish(self, config, components, recreate=False):
"""
Restore publish from config file
"""
if "all" in components:
components = []
try:
self.load()
publish = True
except NoSuchPublish:
publish = False
... | [
"def",
"restore_publish",
"(",
"self",
",",
"config",
",",
"components",
",",
"recreate",
"=",
"False",
")",
":",
"if",
"\"all\"",
"in",
"components",
":",
"components",
"=",
"[",
"]",
"try",
":",
"self",
".",
"load",
"(",
")",
"publish",
"=",
"True",
... | Restore publish from config file | [
"Restore",
"publish",
"from",
"config",
"file"
] | train | https://github.com/tcpcloud/python-aptly/blob/7eb4ce1c508666bad0e6a0d4c5c561b1485ed558/aptly/publisher/__init__.py#L467-L541 |
tcpcloud/python-aptly | aptly/publisher/__init__.py | Publish.load | def load(self):
"""
Load publish info from remote
"""
publish = self._get_publish()
self.architectures = publish['Architectures']
for source in publish['Sources']:
component = source['Component']
snapshot = source['Name']
self.publish_s... | python | def load(self):
"""
Load publish info from remote
"""
publish = self._get_publish()
self.architectures = publish['Architectures']
for source in publish['Sources']:
component = source['Component']
snapshot = source['Name']
self.publish_s... | [
"def",
"load",
"(",
"self",
")",
":",
"publish",
"=",
"self",
".",
"_get_publish",
"(",
")",
"self",
".",
"architectures",
"=",
"publish",
"[",
"'Architectures'",
"]",
"for",
"source",
"in",
"publish",
"[",
"'Sources'",
"]",
":",
"component",
"=",
"sourc... | Load publish info from remote | [
"Load",
"publish",
"info",
"from",
"remote"
] | train | https://github.com/tcpcloud/python-aptly/blob/7eb4ce1c508666bad0e6a0d4c5c561b1485ed558/aptly/publisher/__init__.py#L543-L559 |
tcpcloud/python-aptly | aptly/publisher/__init__.py | Publish.get_packages | def get_packages(self, component=None, components=[], packages=None):
"""
Return package refs for given components
"""
if component:
components = [component]
package_refs = []
for snapshot in self.publish_snapshots:
if component and snapshot['Comp... | python | def get_packages(self, component=None, components=[], packages=None):
"""
Return package refs for given components
"""
if component:
components = [component]
package_refs = []
for snapshot in self.publish_snapshots:
if component and snapshot['Comp... | [
"def",
"get_packages",
"(",
"self",
",",
"component",
"=",
"None",
",",
"components",
"=",
"[",
"]",
",",
"packages",
"=",
"None",
")",
":",
"if",
"component",
":",
"components",
"=",
"[",
"component",
"]",
"package_refs",
"=",
"[",
"]",
"for",
"snapsh... | Return package refs for given components | [
"Return",
"package",
"refs",
"for",
"given",
"components"
] | train | https://github.com/tcpcloud/python-aptly/blob/7eb4ce1c508666bad0e6a0d4c5c561b1485ed558/aptly/publisher/__init__.py#L561-L583 |
tcpcloud/python-aptly | aptly/publisher/__init__.py | Publish.parse_package_ref | def parse_package_ref(self, ref):
"""
Return tuple of architecture, package_name, version, id
"""
if not ref:
return None
parsed = re.match('(.*)\ (.*)\ (.*)\ (.*)', ref)
return parsed.groups() | python | def parse_package_ref(self, ref):
"""
Return tuple of architecture, package_name, version, id
"""
if not ref:
return None
parsed = re.match('(.*)\ (.*)\ (.*)\ (.*)', ref)
return parsed.groups() | [
"def",
"parse_package_ref",
"(",
"self",
",",
"ref",
")",
":",
"if",
"not",
"ref",
":",
"return",
"None",
"parsed",
"=",
"re",
".",
"match",
"(",
"'(.*)\\ (.*)\\ (.*)\\ (.*)'",
",",
"ref",
")",
"return",
"parsed",
".",
"groups",
"(",
")"
] | Return tuple of architecture, package_name, version, id | [
"Return",
"tuple",
"of",
"architecture",
"package_name",
"version",
"id"
] | train | https://github.com/tcpcloud/python-aptly/blob/7eb4ce1c508666bad0e6a0d4c5c561b1485ed558/aptly/publisher/__init__.py#L585-L592 |
tcpcloud/python-aptly | aptly/publisher/__init__.py | Publish.add | def add(self, snapshot, component='main'):
"""
Add snapshot of component to publish
"""
try:
self.components[component].append(snapshot)
except KeyError:
self.components[component] = [snapshot] | python | def add(self, snapshot, component='main'):
"""
Add snapshot of component to publish
"""
try:
self.components[component].append(snapshot)
except KeyError:
self.components[component] = [snapshot] | [
"def",
"add",
"(",
"self",
",",
"snapshot",
",",
"component",
"=",
"'main'",
")",
":",
"try",
":",
"self",
".",
"components",
"[",
"component",
"]",
".",
"append",
"(",
"snapshot",
")",
"except",
"KeyError",
":",
"self",
".",
"components",
"[",
"compon... | Add snapshot of component to publish | [
"Add",
"snapshot",
"of",
"component",
"to",
"publish"
] | train | https://github.com/tcpcloud/python-aptly/blob/7eb4ce1c508666bad0e6a0d4c5c561b1485ed558/aptly/publisher/__init__.py#L594-L601 |
tcpcloud/python-aptly | aptly/publisher/__init__.py | Publish._find_snapshot | def _find_snapshot(self, name):
"""
Find snapshot on remote by name or regular expression
"""
remote_snapshots = self._get_snapshots(self.client)
for remote in reversed(remote_snapshots):
if remote["Name"] == name or \
re.match(name, remote["Name"]... | python | def _find_snapshot(self, name):
"""
Find snapshot on remote by name or regular expression
"""
remote_snapshots = self._get_snapshots(self.client)
for remote in reversed(remote_snapshots):
if remote["Name"] == name or \
re.match(name, remote["Name"]... | [
"def",
"_find_snapshot",
"(",
"self",
",",
"name",
")",
":",
"remote_snapshots",
"=",
"self",
".",
"_get_snapshots",
"(",
"self",
".",
"client",
")",
"for",
"remote",
"in",
"reversed",
"(",
"remote_snapshots",
")",
":",
"if",
"remote",
"[",
"\"Name\"",
"]"... | Find snapshot on remote by name or regular expression | [
"Find",
"snapshot",
"on",
"remote",
"by",
"name",
"or",
"regular",
"expression"
] | train | https://github.com/tcpcloud/python-aptly/blob/7eb4ce1c508666bad0e6a0d4c5c561b1485ed558/aptly/publisher/__init__.py#L603-L612 |
tcpcloud/python-aptly | aptly/publisher/__init__.py | Publish._get_source_snapshots | def _get_source_snapshots(self, snapshot, fallback_self=False):
"""
Get list of source snapshot names of given snapshot
TODO: we have to decide by description at the moment
"""
if not snapshot:
return []
source_snapshots = re.findall(r"'([\w\d\.-]+)'", snaps... | python | def _get_source_snapshots(self, snapshot, fallback_self=False):
"""
Get list of source snapshot names of given snapshot
TODO: we have to decide by description at the moment
"""
if not snapshot:
return []
source_snapshots = re.findall(r"'([\w\d\.-]+)'", snaps... | [
"def",
"_get_source_snapshots",
"(",
"self",
",",
"snapshot",
",",
"fallback_self",
"=",
"False",
")",
":",
"if",
"not",
"snapshot",
":",
"return",
"[",
"]",
"source_snapshots",
"=",
"re",
".",
"findall",
"(",
"r\"'([\\w\\d\\.-]+)'\"",
",",
"snapshot",
"[",
... | Get list of source snapshot names of given snapshot
TODO: we have to decide by description at the moment | [
"Get",
"list",
"of",
"source",
"snapshot",
"names",
"of",
"given",
"snapshot"
] | train | https://github.com/tcpcloud/python-aptly/blob/7eb4ce1c508666bad0e6a0d4c5c561b1485ed558/aptly/publisher/__init__.py#L614-L628 |
tcpcloud/python-aptly | aptly/publisher/__init__.py | Publish.merge_snapshots | def merge_snapshots(self):
"""
Create component snapshots by merging other snapshots of same component
"""
self.publish_snapshots = []
for component, snapshots in self.components.items():
if len(snapshots) <= 1:
# Only one snapshot, no need to merge
... | python | def merge_snapshots(self):
"""
Create component snapshots by merging other snapshots of same component
"""
self.publish_snapshots = []
for component, snapshots in self.components.items():
if len(snapshots) <= 1:
# Only one snapshot, no need to merge
... | [
"def",
"merge_snapshots",
"(",
"self",
")",
":",
"self",
".",
"publish_snapshots",
"=",
"[",
"]",
"for",
"component",
",",
"snapshots",
"in",
"self",
".",
"components",
".",
"items",
"(",
")",
":",
"if",
"len",
"(",
"snapshots",
")",
"<=",
"1",
":",
... | Create component snapshots by merging other snapshots of same component | [
"Create",
"component",
"snapshots",
"by",
"merging",
"other",
"snapshots",
"of",
"same",
"component"
] | train | https://github.com/tcpcloud/python-aptly/blob/7eb4ce1c508666bad0e6a0d4c5c561b1485ed558/aptly/publisher/__init__.py#L630-L690 |
ejhigson/nestcheck | nestcheck/io_utils.py | timing_decorator | def timing_decorator(func):
"""Prints the time func takes to execute."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""
Wrapper for printing execution time.
Parameters
----------
print_time: bool, optional
whether or not to print time function t... | python | def timing_decorator(func):
"""Prints the time func takes to execute."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""
Wrapper for printing execution time.
Parameters
----------
print_time: bool, optional
whether or not to print time function t... | [
"def",
"timing_decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Wrapper for printing execution time.\n\n Parameters\n ----------\n... | Prints the time func takes to execute. | [
"Prints",
"the",
"time",
"func",
"takes",
"to",
"execute",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/io_utils.py#L14-L36 |
ejhigson/nestcheck | nestcheck/io_utils.py | save_load_result | def save_load_result(func):
"""Saves and/or loads func output (must be picklable)."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""
Default behavior is no saving and loading. Specify save_name to save
and load.
Parameters
----------
save_name: str,... | python | def save_load_result(func):
"""Saves and/or loads func output (must be picklable)."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""
Default behavior is no saving and loading. Specify save_name to save
and load.
Parameters
----------
save_name: str,... | [
"def",
"save_load_result",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Default behavior is no saving and loading. Specify save_name to save\n an... | Saves and/or loads func output (must be picklable). | [
"Saves",
"and",
"/",
"or",
"loads",
"func",
"output",
"(",
"must",
"be",
"picklable",
")",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/io_utils.py#L39-L97 |
ejhigson/nestcheck | nestcheck/io_utils.py | pickle_save | def pickle_save(data, name, **kwargs):
"""Saves object with pickle.
Parameters
----------
data: anything picklable
Object to save.
name: str
Path to save to (includes dir, excludes extension).
extension: str, optional
File extension.
overwrite existing: bool, optiona... | python | def pickle_save(data, name, **kwargs):
"""Saves object with pickle.
Parameters
----------
data: anything picklable
Object to save.
name: str
Path to save to (includes dir, excludes extension).
extension: str, optional
File extension.
overwrite existing: bool, optiona... | [
"def",
"pickle_save",
"(",
"data",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"extension",
"=",
"kwargs",
".",
"pop",
"(",
"'extension'",
",",
"'.pkl'",
")",
"overwrite_existing",
"=",
"kwargs",
".",
"pop",
"(",
"'overwrite_existing'",
",",
"True",
... | Saves object with pickle.
Parameters
----------
data: anything picklable
Object to save.
name: str
Path to save to (includes dir, excludes extension).
extension: str, optional
File extension.
overwrite existing: bool, optional
When the save path already contains ... | [
"Saves",
"object",
"with",
"pickle",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/io_utils.py#L101-L142 |
ejhigson/nestcheck | nestcheck/io_utils.py | pickle_load | def pickle_load(name, extension='.pkl'):
"""Load data with pickle.
Parameters
----------
name: str
Path to save to (includes dir, excludes extension).
extension: str, optional
File extension.
Returns
-------
Contents of file path.
"""
filename = name + extension... | python | def pickle_load(name, extension='.pkl'):
"""Load data with pickle.
Parameters
----------
name: str
Path to save to (includes dir, excludes extension).
extension: str, optional
File extension.
Returns
-------
Contents of file path.
"""
filename = name + extension... | [
"def",
"pickle_load",
"(",
"name",
",",
"extension",
"=",
"'.pkl'",
")",
":",
"filename",
"=",
"name",
"+",
"extension",
"infile",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
"data",
"=",
"pickle",
".",
"load",
"(",
"infile",
")",
"infile",
".",
... | Load data with pickle.
Parameters
----------
name: str
Path to save to (includes dir, excludes extension).
extension: str, optional
File extension.
Returns
-------
Contents of file path. | [
"Load",
"data",
"with",
"pickle",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/io_utils.py#L146-L164 |
ejhigson/nestcheck | nestcheck/error_analysis.py | bootstrap_resample_run | def bootstrap_resample_run(ns_run, threads=None, ninit_sep=False,
random_seed=False):
"""Bootstrap resamples threads of nested sampling run, returning a new
(resampled) nested sampling run.
Get the individual threads for a nested sampling run.
Parameters
----------
n... | python | def bootstrap_resample_run(ns_run, threads=None, ninit_sep=False,
random_seed=False):
"""Bootstrap resamples threads of nested sampling run, returning a new
(resampled) nested sampling run.
Get the individual threads for a nested sampling run.
Parameters
----------
n... | [
"def",
"bootstrap_resample_run",
"(",
"ns_run",
",",
"threads",
"=",
"None",
",",
"ninit_sep",
"=",
"False",
",",
"random_seed",
"=",
"False",
")",
":",
"if",
"random_seed",
"is",
"not",
"False",
":",
"# save the random state so we don't affect other bits of the code"... | Bootstrap resamples threads of nested sampling run, returning a new
(resampled) nested sampling run.
Get the individual threads for a nested sampling run.
Parameters
----------
ns_run: dict
Nested sampling run dictionary.
threads: None or list of numpy arrays, optional
ninit_sep: b... | [
"Bootstrap",
"resamples",
"threads",
"of",
"nested",
"sampling",
"run",
"returning",
"a",
"new",
"(",
"resampled",
")",
"nested",
"sampling",
"run",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/error_analysis.py#L17-L80 |
ejhigson/nestcheck | nestcheck/error_analysis.py | run_std_bootstrap | def run_std_bootstrap(ns_run, estimator_list, **kwargs):
"""
Uses bootstrap resampling to calculate an estimate of the
standard deviation of the distribution of sampling errors (the
uncertainty on the calculation) for a single nested sampling run.
For more details about bootstrap resampling for est... | python | def run_std_bootstrap(ns_run, estimator_list, **kwargs):
"""
Uses bootstrap resampling to calculate an estimate of the
standard deviation of the distribution of sampling errors (the
uncertainty on the calculation) for a single nested sampling run.
For more details about bootstrap resampling for est... | [
"def",
"run_std_bootstrap",
"(",
"ns_run",
",",
"estimator_list",
",",
"*",
"*",
"kwargs",
")",
":",
"bs_values",
"=",
"run_bootstrap_values",
"(",
"ns_run",
",",
"estimator_list",
",",
"*",
"*",
"kwargs",
")",
"stds",
"=",
"np",
".",
"zeros",
"(",
"bs_val... | Uses bootstrap resampling to calculate an estimate of the
standard deviation of the distribution of sampling errors (the
uncertainty on the calculation) for a single nested sampling run.
For more details about bootstrap resampling for estimating sampling
errors see 'Sampling errors in nested sampling p... | [
"Uses",
"bootstrap",
"resampling",
"to",
"calculate",
"an",
"estimate",
"of",
"the",
"standard",
"deviation",
"of",
"the",
"distribution",
"of",
"sampling",
"errors",
"(",
"the",
"uncertainty",
"on",
"the",
"calculation",
")",
"for",
"a",
"single",
"nested",
"... | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/error_analysis.py#L83-L114 |
ejhigson/nestcheck | nestcheck/error_analysis.py | run_bootstrap_values | def run_bootstrap_values(ns_run, estimator_list, **kwargs):
"""Uses bootstrap resampling to calculate an estimate of the
standard deviation of the distribution of sampling errors (the
uncertainty on the calculation) for a single nested sampling run.
For more details about bootstrap resampling for estim... | python | def run_bootstrap_values(ns_run, estimator_list, **kwargs):
"""Uses bootstrap resampling to calculate an estimate of the
standard deviation of the distribution of sampling errors (the
uncertainty on the calculation) for a single nested sampling run.
For more details about bootstrap resampling for estim... | [
"def",
"run_bootstrap_values",
"(",
"ns_run",
",",
"estimator_list",
",",
"*",
"*",
"kwargs",
")",
":",
"ninit_sep",
"=",
"kwargs",
".",
"pop",
"(",
"'ninit_sep'",
",",
"False",
")",
"flip_skew",
"=",
"kwargs",
".",
"pop",
"(",
"'flip_skew'",
",",
"True",
... | Uses bootstrap resampling to calculate an estimate of the
standard deviation of the distribution of sampling errors (the
uncertainty on the calculation) for a single nested sampling run.
For more details about bootstrap resampling for estimating sampling
errors see 'Sampling errors in nested sampling p... | [
"Uses",
"bootstrap",
"resampling",
"to",
"calculate",
"an",
"estimate",
"of",
"the",
"standard",
"deviation",
"of",
"the",
"distribution",
"of",
"sampling",
"errors",
"(",
"the",
"uncertainty",
"on",
"the",
"calculation",
")",
"for",
"a",
"single",
"nested",
"... | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/error_analysis.py#L117-L178 |
ejhigson/nestcheck | nestcheck/error_analysis.py | run_ci_bootstrap | def run_ci_bootstrap(ns_run, estimator_list, **kwargs):
"""Uses bootstrap resampling to calculate credible intervals on the
distribution of sampling errors (the uncertainty on the calculation)
for a single nested sampling run.
For more details about bootstrap resampling for estimating sampling
erro... | python | def run_ci_bootstrap(ns_run, estimator_list, **kwargs):
"""Uses bootstrap resampling to calculate credible intervals on the
distribution of sampling errors (the uncertainty on the calculation)
for a single nested sampling run.
For more details about bootstrap resampling for estimating sampling
erro... | [
"def",
"run_ci_bootstrap",
"(",
"ns_run",
",",
"estimator_list",
",",
"*",
"*",
"kwargs",
")",
":",
"cred_int",
"=",
"kwargs",
".",
"pop",
"(",
"'cred_int'",
")",
"# No default, must specify",
"bs_values",
"=",
"run_bootstrap_values",
"(",
"ns_run",
",",
"estima... | Uses bootstrap resampling to calculate credible intervals on the
distribution of sampling errors (the uncertainty on the calculation)
for a single nested sampling run.
For more details about bootstrap resampling for estimating sampling
errors see 'Sampling errors in nested sampling parameter estimation... | [
"Uses",
"bootstrap",
"resampling",
"to",
"calculate",
"credible",
"intervals",
"on",
"the",
"distribution",
"of",
"sampling",
"errors",
"(",
"the",
"uncertainty",
"on",
"the",
"calculation",
")",
"for",
"a",
"single",
"nested",
"sampling",
"run",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/error_analysis.py#L181-L221 |
ejhigson/nestcheck | nestcheck/error_analysis.py | run_std_simulate | def run_std_simulate(ns_run, estimator_list, n_simulate=None):
"""Uses the 'simulated weights' method to calculate an estimate of the
standard deviation of the distribution of sampling errors (the
uncertainty on the calculation) for a single nested sampling run.
Note that the simulated weights method i... | python | def run_std_simulate(ns_run, estimator_list, n_simulate=None):
"""Uses the 'simulated weights' method to calculate an estimate of the
standard deviation of the distribution of sampling errors (the
uncertainty on the calculation) for a single nested sampling run.
Note that the simulated weights method i... | [
"def",
"run_std_simulate",
"(",
"ns_run",
",",
"estimator_list",
",",
"n_simulate",
"=",
"None",
")",
":",
"assert",
"n_simulate",
"is",
"not",
"None",
",",
"'run_std_simulate: must specify n_simulate'",
"all_values",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(... | Uses the 'simulated weights' method to calculate an estimate of the
standard deviation of the distribution of sampling errors (the
uncertainty on the calculation) for a single nested sampling run.
Note that the simulated weights method is not accurate for parameter
estimation calculations.
For mor... | [
"Uses",
"the",
"simulated",
"weights",
"method",
"to",
"calculate",
"an",
"estimate",
"of",
"the",
"standard",
"deviation",
"of",
"the",
"distribution",
"of",
"sampling",
"errors",
"(",
"the",
"uncertainty",
"on",
"the",
"calculation",
")",
"for",
"a",
"single... | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/error_analysis.py#L224-L260 |
ejhigson/nestcheck | nestcheck/error_analysis.py | implementation_std | def implementation_std(vals_std, vals_std_u, bs_std, bs_std_u, **kwargs):
r"""Estimates varaition of results due to implementation-specific
effects. See 'nestcheck: diagnostic tests for nested sampling calculations'
(Higson et al. 2019) for more details.
Uncertainties on the output are calculated numer... | python | def implementation_std(vals_std, vals_std_u, bs_std, bs_std_u, **kwargs):
r"""Estimates varaition of results due to implementation-specific
effects. See 'nestcheck: diagnostic tests for nested sampling calculations'
(Higson et al. 2019) for more details.
Uncertainties on the output are calculated numer... | [
"def",
"implementation_std",
"(",
"vals_std",
",",
"vals_std_u",
",",
"bs_std",
",",
"bs_std_u",
",",
"*",
"*",
"kwargs",
")",
":",
"nsim",
"=",
"kwargs",
".",
"pop",
"(",
"'nsim'",
",",
"1000000",
")",
"random_seed",
"=",
"kwargs",
".",
"pop",
"(",
"'... | r"""Estimates varaition of results due to implementation-specific
effects. See 'nestcheck: diagnostic tests for nested sampling calculations'
(Higson et al. 2019) for more details.
Uncertainties on the output are calculated numerically using the fact
that (from central limit theorem) our uncertainties ... | [
"r",
"Estimates",
"varaition",
"of",
"results",
"due",
"to",
"implementation",
"-",
"specific",
"effects",
".",
"See",
"nestcheck",
":",
"diagnostic",
"tests",
"for",
"nested",
"sampling",
"calculations",
"(",
"Higson",
"et",
"al",
".",
"2019",
")",
"for",
"... | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/error_analysis.py#L267-L332 |
ejhigson/nestcheck | nestcheck/error_analysis.py | run_thread_values | def run_thread_values(run, estimator_list):
"""Helper function for parallelising thread_values_df.
Parameters
----------
ns_run: dict
Nested sampling run dictionary.
estimator_list: list of functions
Returns
-------
vals_array: numpy array
Array of estimator values for ... | python | def run_thread_values(run, estimator_list):
"""Helper function for parallelising thread_values_df.
Parameters
----------
ns_run: dict
Nested sampling run dictionary.
estimator_list: list of functions
Returns
-------
vals_array: numpy array
Array of estimator values for ... | [
"def",
"run_thread_values",
"(",
"run",
",",
"estimator_list",
")",
":",
"threads",
"=",
"nestcheck",
".",
"ns_run_utils",
".",
"get_run_threads",
"(",
"run",
")",
"vals_list",
"=",
"[",
"nestcheck",
".",
"ns_run_utils",
".",
"run_estimators",
"(",
"th",
",",
... | Helper function for parallelising thread_values_df.
Parameters
----------
ns_run: dict
Nested sampling run dictionary.
estimator_list: list of functions
Returns
-------
vals_array: numpy array
Array of estimator values for each thread.
Has shape (len(estimator_list)... | [
"Helper",
"function",
"for",
"parallelising",
"thread_values_df",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/error_analysis.py#L335-L355 |
ejhigson/nestcheck | nestcheck/error_analysis.py | pairwise_distances | def pairwise_distances(dist_list, earth_mover_dist=True, energy_dist=True):
"""Applies statistical_distances to each unique pair of distribution
samples in dist_list.
Parameters
----------
dist_list: list of 1d arrays
earth_mover_dist: bool, optional
Passed to statistical_distances.
... | python | def pairwise_distances(dist_list, earth_mover_dist=True, energy_dist=True):
"""Applies statistical_distances to each unique pair of distribution
samples in dist_list.
Parameters
----------
dist_list: list of 1d arrays
earth_mover_dist: bool, optional
Passed to statistical_distances.
... | [
"def",
"pairwise_distances",
"(",
"dist_list",
",",
"earth_mover_dist",
"=",
"True",
",",
"energy_dist",
"=",
"True",
")",
":",
"out",
"=",
"[",
"]",
"index",
"=",
"[",
"]",
"for",
"i",
",",
"samp_i",
"in",
"enumerate",
"(",
"dist_list",
")",
":",
"for... | Applies statistical_distances to each unique pair of distribution
samples in dist_list.
Parameters
----------
dist_list: list of 1d arrays
earth_mover_dist: bool, optional
Passed to statistical_distances.
energy_dist: bool, optional
Passed to statistical_distances.
Returns
... | [
"Applies",
"statistical_distances",
"to",
"each",
"unique",
"pair",
"of",
"distribution",
"samples",
"in",
"dist_list",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/error_analysis.py#L358-L394 |
ejhigson/nestcheck | nestcheck/error_analysis.py | statistical_distances | def statistical_distances(samples1, samples2, earth_mover_dist=True,
energy_dist=True):
"""Compute measures of the statistical distance between samples.
Parameters
----------
samples1: 1d array
samples2: 1d array
earth_mover_dist: bool, optional
Whether or not ... | python | def statistical_distances(samples1, samples2, earth_mover_dist=True,
energy_dist=True):
"""Compute measures of the statistical distance between samples.
Parameters
----------
samples1: 1d array
samples2: 1d array
earth_mover_dist: bool, optional
Whether or not ... | [
"def",
"statistical_distances",
"(",
"samples1",
",",
"samples2",
",",
"earth_mover_dist",
"=",
"True",
",",
"energy_dist",
"=",
"True",
")",
":",
"out",
"=",
"[",
"]",
"temp",
"=",
"scipy",
".",
"stats",
".",
"ks_2samp",
"(",
"samples1",
",",
"samples2",
... | Compute measures of the statistical distance between samples.
Parameters
----------
samples1: 1d array
samples2: 1d array
earth_mover_dist: bool, optional
Whether or not to compute the Earth mover's distance between the
samples.
energy_dist: bool, optional
Whether or not... | [
"Compute",
"measures",
"of",
"the",
"statistical",
"distance",
"between",
"samples",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/error_analysis.py#L397-L423 |
ejhigson/nestcheck | nestcheck/dummy_data.py | get_dummy_thread | def get_dummy_thread(nsamples, **kwargs):
"""Generate dummy data for a single nested sampling thread.
Log-likelihood values of points are generated from a uniform distribution
in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is
not -np.inf). Theta values of each point are each g... | python | def get_dummy_thread(nsamples, **kwargs):
"""Generate dummy data for a single nested sampling thread.
Log-likelihood values of points are generated from a uniform distribution
in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is
not -np.inf). Theta values of each point are each g... | [
"def",
"get_dummy_thread",
"(",
"nsamples",
",",
"*",
"*",
"kwargs",
")",
":",
"seed",
"=",
"kwargs",
".",
"pop",
"(",
"'seed'",
",",
"False",
")",
"ndim",
"=",
"kwargs",
".",
"pop",
"(",
"'ndim'",
",",
"2",
")",
"logl_start",
"=",
"kwargs",
".",
"... | Generate dummy data for a single nested sampling thread.
Log-likelihood values of points are generated from a uniform distribution
in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is
not -np.inf). Theta values of each point are each generated from a uniform
distribution in (0, 1... | [
"Generate",
"dummy",
"data",
"for",
"a",
"single",
"nested",
"sampling",
"thread",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/dummy_data.py#L11-L47 |
ejhigson/nestcheck | nestcheck/dummy_data.py | get_dummy_run | def get_dummy_run(nthread, nsamples, **kwargs):
"""Generate dummy data for a nested sampling run.
Log-likelihood values of points are generated from a uniform distribution
in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is
not -np.inf). Theta values of each point are each gener... | python | def get_dummy_run(nthread, nsamples, **kwargs):
"""Generate dummy data for a nested sampling run.
Log-likelihood values of points are generated from a uniform distribution
in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is
not -np.inf). Theta values of each point are each gener... | [
"def",
"get_dummy_run",
"(",
"nthread",
",",
"nsamples",
",",
"*",
"*",
"kwargs",
")",
":",
"seed",
"=",
"kwargs",
".",
"pop",
"(",
"'seed'",
",",
"False",
")",
"ndim",
"=",
"kwargs",
".",
"pop",
"(",
"'ndim'",
",",
"2",
")",
"logl_start",
"=",
"kw... | Generate dummy data for a nested sampling run.
Log-likelihood values of points are generated from a uniform distribution
in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is
not -np.inf). Theta values of each point are each generated from a uniform
distribution in (0, 1).
Pa... | [
"Generate",
"dummy",
"data",
"for",
"a",
"nested",
"sampling",
"run",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/dummy_data.py#L50-L96 |
ejhigson/nestcheck | nestcheck/dummy_data.py | get_dummy_dynamic_run | def get_dummy_dynamic_run(nsamples, **kwargs):
"""Generate dummy data for a dynamic nested sampling run.
Loglikelihood values of points are generated from a uniform distribution
in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is
not -np.inf). Theta values of each point are each... | python | def get_dummy_dynamic_run(nsamples, **kwargs):
"""Generate dummy data for a dynamic nested sampling run.
Loglikelihood values of points are generated from a uniform distribution
in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is
not -np.inf). Theta values of each point are each... | [
"def",
"get_dummy_dynamic_run",
"(",
"nsamples",
",",
"*",
"*",
"kwargs",
")",
":",
"seed",
"=",
"kwargs",
".",
"pop",
"(",
"'seed'",
",",
"False",
")",
"ndim",
"=",
"kwargs",
".",
"pop",
"(",
"'ndim'",
",",
"2",
")",
"nthread_init",
"=",
"kwargs",
"... | Generate dummy data for a dynamic nested sampling run.
Loglikelihood values of points are generated from a uniform distribution
in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is
not -np.inf). Theta values of each point are each generated from a uniform
distribution in (0, 1).
... | [
"Generate",
"dummy",
"data",
"for",
"a",
"dynamic",
"nested",
"sampling",
"run",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/dummy_data.py#L99-L148 |
ejhigson/nestcheck | setup.py | get_long_description | def get_long_description():
"""Get PyPI long description from the .rst file."""
pkg_dir = get_package_dir()
with open(os.path.join(pkg_dir, '.pypi_long_desc.rst')) as readme_file:
long_description = readme_file.read()
return long_description | python | def get_long_description():
"""Get PyPI long description from the .rst file."""
pkg_dir = get_package_dir()
with open(os.path.join(pkg_dir, '.pypi_long_desc.rst')) as readme_file:
long_description = readme_file.read()
return long_description | [
"def",
"get_long_description",
"(",
")",
":",
"pkg_dir",
"=",
"get_package_dir",
"(",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"pkg_dir",
",",
"'.pypi_long_desc.rst'",
")",
")",
"as",
"readme_file",
":",
"long_description",
"=",
"readme... | Get PyPI long description from the .rst file. | [
"Get",
"PyPI",
"long",
"description",
"from",
"the",
".",
"rst",
"file",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/setup.py#L16-L21 |
ejhigson/nestcheck | setup.py | get_version | def get_version():
"""Get single-source __version__."""
pkg_dir = get_package_dir()
with open(os.path.join(pkg_dir, 'nestcheck/_version.py')) as ver_file:
string = ver_file.read()
return string.strip().replace('__version__ = ', '').replace('\'', '') | python | def get_version():
"""Get single-source __version__."""
pkg_dir = get_package_dir()
with open(os.path.join(pkg_dir, 'nestcheck/_version.py')) as ver_file:
string = ver_file.read()
return string.strip().replace('__version__ = ', '').replace('\'', '') | [
"def",
"get_version",
"(",
")",
":",
"pkg_dir",
"=",
"get_package_dir",
"(",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"pkg_dir",
",",
"'nestcheck/_version.py'",
")",
")",
"as",
"ver_file",
":",
"string",
"=",
"ver_file",
".",
"read"... | Get single-source __version__. | [
"Get",
"single",
"-",
"source",
"__version__",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/setup.py#L24-L29 |
ejhigson/nestcheck | nestcheck/plots.py | plot_run_nlive | def plot_run_nlive(method_names, run_dict, **kwargs):
"""Plot the allocations of live points as a function of logX for the input
sets of nested sampling runs of the type used in the dynamic nested
sampling paper (Higson et al. 2019).
Plots also include analytically calculated distributions of relative
... | python | def plot_run_nlive(method_names, run_dict, **kwargs):
"""Plot the allocations of live points as a function of logX for the input
sets of nested sampling runs of the type used in the dynamic nested
sampling paper (Higson et al. 2019).
Plots also include analytically calculated distributions of relative
... | [
"def",
"plot_run_nlive",
"(",
"method_names",
",",
"run_dict",
",",
"*",
"*",
"kwargs",
")",
":",
"logx_given_logl",
"=",
"kwargs",
".",
"pop",
"(",
"'logx_given_logl'",
",",
"None",
")",
"logl_given_logx",
"=",
"kwargs",
".",
"pop",
"(",
"'logl_given_logx'",
... | Plot the allocations of live points as a function of logX for the input
sets of nested sampling runs of the type used in the dynamic nested
sampling paper (Higson et al. 2019).
Plots also include analytically calculated distributions of relative
posterior mass and relative posterior mass remaining.
... | [
"Plot",
"the",
"allocations",
"of",
"live",
"points",
"as",
"a",
"function",
"of",
"logX",
"for",
"the",
"input",
"sets",
"of",
"nested",
"sampling",
"runs",
"of",
"the",
"type",
"used",
"in",
"the",
"dynamic",
"nested",
"sampling",
"paper",
"(",
"Higson",... | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/plots.py#L21-L154 |
ejhigson/nestcheck | nestcheck/plots.py | kde_plot_df | def kde_plot_df(df, xlims=None, **kwargs):
"""Plots kde estimates of distributions of samples in each cell of the
input pandas DataFrame.
There is one subplot for each dataframe column, and on each subplot there
is one kde line.
Parameters
----------
df: pandas data frame
Each cell... | python | def kde_plot_df(df, xlims=None, **kwargs):
"""Plots kde estimates of distributions of samples in each cell of the
input pandas DataFrame.
There is one subplot for each dataframe column, and on each subplot there
is one kde line.
Parameters
----------
df: pandas data frame
Each cell... | [
"def",
"kde_plot_df",
"(",
"df",
",",
"xlims",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"xlims",
"is",
"None",
"or",
"isinstance",
"(",
"xlims",
",",
"dict",
")",
"figsize",
"=",
"kwargs",
".",
"pop",
"(",
"'figsize'",
",",
"(",
"6... | Plots kde estimates of distributions of samples in each cell of the
input pandas DataFrame.
There is one subplot for each dataframe column, and on each subplot there
is one kde line.
Parameters
----------
df: pandas data frame
Each cell must contain a 1d numpy array of samples.
xli... | [
"Plots",
"kde",
"estimates",
"of",
"distributions",
"of",
"samples",
"in",
"each",
"cell",
"of",
"the",
"input",
"pandas",
"DataFrame",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/plots.py#L157-L232 |
ejhigson/nestcheck | nestcheck/plots.py | bs_param_dists | def bs_param_dists(run_list, **kwargs):
"""Creates posterior distributions and their bootstrap error functions for
input runs and estimators.
For a more detailed description and some example use cases, see 'nestcheck:
diagnostic tests for nested sampling calculations' (Higson et al. 2019).
Paramet... | python | def bs_param_dists(run_list, **kwargs):
"""Creates posterior distributions and their bootstrap error functions for
input runs and estimators.
For a more detailed description and some example use cases, see 'nestcheck:
diagnostic tests for nested sampling calculations' (Higson et al. 2019).
Paramet... | [
"def",
"bs_param_dists",
"(",
"run_list",
",",
"*",
"*",
"kwargs",
")",
":",
"fthetas",
"=",
"kwargs",
".",
"pop",
"(",
"'fthetas'",
",",
"[",
"lambda",
"theta",
":",
"theta",
"[",
":",
",",
"0",
"]",
",",
"lambda",
"theta",
":",
"theta",
"[",
":",... | Creates posterior distributions and their bootstrap error functions for
input runs and estimators.
For a more detailed description and some example use cases, see 'nestcheck:
diagnostic tests for nested sampling calculations' (Higson et al. 2019).
Parameters
----------
run_list: dict or list o... | [
"Creates",
"posterior",
"distributions",
"and",
"their",
"bootstrap",
"error",
"functions",
"for",
"input",
"runs",
"and",
"estimators",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/plots.py#L235-L346 |
ejhigson/nestcheck | nestcheck/plots.py | param_logx_diagram | def param_logx_diagram(run_list, **kwargs):
"""Creates diagrams of a nested sampling run's evolution as it iterates
towards higher likelihoods, expressed as a function of log X, where X(L) is
the fraction of the prior volume with likelihood greater than some value L.
For a more detailed description and... | python | def param_logx_diagram(run_list, **kwargs):
"""Creates diagrams of a nested sampling run's evolution as it iterates
towards higher likelihoods, expressed as a function of log X, where X(L) is
the fraction of the prior volume with likelihood greater than some value L.
For a more detailed description and... | [
"def",
"param_logx_diagram",
"(",
"run_list",
",",
"*",
"*",
"kwargs",
")",
":",
"fthetas",
"=",
"kwargs",
".",
"pop",
"(",
"'fthetas'",
",",
"[",
"lambda",
"theta",
":",
"theta",
"[",
":",
",",
"0",
"]",
",",
"lambda",
"theta",
":",
"theta",
"[",
... | Creates diagrams of a nested sampling run's evolution as it iterates
towards higher likelihoods, expressed as a function of log X, where X(L) is
the fraction of the prior volume with likelihood greater than some value L.
For a more detailed description and some example use cases, see 'nestcheck:
diagno... | [
"Creates",
"diagrams",
"of",
"a",
"nested",
"sampling",
"run",
"s",
"evolution",
"as",
"it",
"iterates",
"towards",
"higher",
"likelihoods",
"expressed",
"as",
"a",
"function",
"of",
"log",
"X",
"where",
"X",
"(",
"L",
")",
"is",
"the",
"fraction",
"of",
... | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/plots.py#L349-L571 |
ejhigson/nestcheck | nestcheck/plots.py | plot_bs_dists | def plot_bs_dists(run, fthetas, axes, **kwargs):
"""Helper function for plotting uncertainties on posterior distributions
using bootstrap resamples and the fgivenx module. Used by bs_param_dists
and param_logx_diagram.
Parameters
----------
run: dict
Nested sampling run to plot.
fth... | python | def plot_bs_dists(run, fthetas, axes, **kwargs):
"""Helper function for plotting uncertainties on posterior distributions
using bootstrap resamples and the fgivenx module. Used by bs_param_dists
and param_logx_diagram.
Parameters
----------
run: dict
Nested sampling run to plot.
fth... | [
"def",
"plot_bs_dists",
"(",
"run",
",",
"fthetas",
",",
"axes",
",",
"*",
"*",
"kwargs",
")",
":",
"ftheta_lims",
"=",
"kwargs",
".",
"pop",
"(",
"'ftheta_lims'",
",",
"[",
"[",
"-",
"1",
",",
"1",
"]",
"]",
"*",
"len",
"(",
"fthetas",
")",
")",... | Helper function for plotting uncertainties on posterior distributions
using bootstrap resamples and the fgivenx module. Used by bs_param_dists
and param_logx_diagram.
Parameters
----------
run: dict
Nested sampling run to plot.
fthetas: list of functions
Quantities to plot. Each... | [
"Helper",
"function",
"for",
"plotting",
"uncertainties",
"on",
"posterior",
"distributions",
"using",
"bootstrap",
"resamples",
"and",
"the",
"fgivenx",
"module",
".",
"Used",
"by",
"bs_param_dists",
"and",
"param_logx_diagram",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/plots.py#L578-L693 |
ejhigson/nestcheck | nestcheck/plots.py | alternate_helper | def alternate_helper(x, alt_samps, func=None):
"""Helper function for making fgivenx plots of functions with 2 array
arguments of variable lengths."""
alt_samps = alt_samps[~np.isnan(alt_samps)]
arg1 = alt_samps[::2]
arg2 = alt_samps[1::2]
return func(x, arg1, arg2) | python | def alternate_helper(x, alt_samps, func=None):
"""Helper function for making fgivenx plots of functions with 2 array
arguments of variable lengths."""
alt_samps = alt_samps[~np.isnan(alt_samps)]
arg1 = alt_samps[::2]
arg2 = alt_samps[1::2]
return func(x, arg1, arg2) | [
"def",
"alternate_helper",
"(",
"x",
",",
"alt_samps",
",",
"func",
"=",
"None",
")",
":",
"alt_samps",
"=",
"alt_samps",
"[",
"~",
"np",
".",
"isnan",
"(",
"alt_samps",
")",
"]",
"arg1",
"=",
"alt_samps",
"[",
":",
":",
"2",
"]",
"arg2",
"=",
"alt... | Helper function for making fgivenx plots of functions with 2 array
arguments of variable lengths. | [
"Helper",
"function",
"for",
"making",
"fgivenx",
"plots",
"of",
"functions",
"with",
"2",
"array",
"arguments",
"of",
"variable",
"lengths",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/plots.py#L696-L702 |
ejhigson/nestcheck | nestcheck/plots.py | weighted_1d_gaussian_kde | def weighted_1d_gaussian_kde(x, samples, weights):
"""Gaussian kde with weighted samples (1d only). Uses Scott bandwidth
factor.
When all the sample weights are equal, this is equivalent to
kde = scipy.stats.gaussian_kde(theta)
return kde(x)
When the weights are not all equal, we compute the ... | python | def weighted_1d_gaussian_kde(x, samples, weights):
"""Gaussian kde with weighted samples (1d only). Uses Scott bandwidth
factor.
When all the sample weights are equal, this is equivalent to
kde = scipy.stats.gaussian_kde(theta)
return kde(x)
When the weights are not all equal, we compute the ... | [
"def",
"weighted_1d_gaussian_kde",
"(",
"x",
",",
"samples",
",",
"weights",
")",
":",
"assert",
"x",
".",
"ndim",
"==",
"1",
"assert",
"samples",
".",
"ndim",
"==",
"1",
"assert",
"samples",
".",
"shape",
"==",
"weights",
".",
"shape",
"# normalise weight... | Gaussian kde with weighted samples (1d only). Uses Scott bandwidth
factor.
When all the sample weights are equal, this is equivalent to
kde = scipy.stats.gaussian_kde(theta)
return kde(x)
When the weights are not all equal, we compute the effective number
of samples as the information content... | [
"Gaussian",
"kde",
"with",
"weighted",
"samples",
"(",
"1d",
"only",
")",
".",
"Uses",
"Scott",
"bandwidth",
"factor",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/plots.py#L705-L761 |
ejhigson/nestcheck | nestcheck/plots.py | rel_posterior_mass | def rel_posterior_mass(logx, logl):
"""Calculate the relative posterior mass for some array of logx values
given the likelihood, prior and number of dimensions.
The posterior mass at each logX value is proportional to L(X)X, where L(X)
is the likelihood.
The weight is returned normalized so that the... | python | def rel_posterior_mass(logx, logl):
"""Calculate the relative posterior mass for some array of logx values
given the likelihood, prior and number of dimensions.
The posterior mass at each logX value is proportional to L(X)X, where L(X)
is the likelihood.
The weight is returned normalized so that the... | [
"def",
"rel_posterior_mass",
"(",
"logx",
",",
"logl",
")",
":",
"logw",
"=",
"logx",
"+",
"logl",
"w_rel",
"=",
"np",
".",
"exp",
"(",
"logw",
"-",
"logw",
".",
"max",
"(",
")",
")",
"w_rel",
"/=",
"np",
".",
"abs",
"(",
"np",
".",
"trapz",
"(... | Calculate the relative posterior mass for some array of logx values
given the likelihood, prior and number of dimensions.
The posterior mass at each logX value is proportional to L(X)X, where L(X)
is the likelihood.
The weight is returned normalized so that the integral of the weight with
respect to... | [
"Calculate",
"the",
"relative",
"posterior",
"mass",
"for",
"some",
"array",
"of",
"logx",
"values",
"given",
"the",
"likelihood",
"prior",
"and",
"number",
"of",
"dimensions",
".",
"The",
"posterior",
"mass",
"at",
"each",
"logX",
"value",
"is",
"proportional... | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/plots.py#L764-L787 |
ejhigson/nestcheck | nestcheck/plots.py | average_by_key | def average_by_key(dict_in, key):
"""Helper function for plot_run_nlive.
Try returning the average of dict_in[key] and, if this does not work or if
key is None, return average of whole dict.
Parameters
----------
dict_in: dict
Values should be arrays.
key: str
Returns
----... | python | def average_by_key(dict_in, key):
"""Helper function for plot_run_nlive.
Try returning the average of dict_in[key] and, if this does not work or if
key is None, return average of whole dict.
Parameters
----------
dict_in: dict
Values should be arrays.
key: str
Returns
----... | [
"def",
"average_by_key",
"(",
"dict_in",
",",
"key",
")",
":",
"if",
"key",
"is",
"None",
":",
"return",
"np",
".",
"mean",
"(",
"np",
".",
"concatenate",
"(",
"list",
"(",
"dict_in",
".",
"values",
"(",
")",
")",
")",
")",
"else",
":",
"try",
":... | Helper function for plot_run_nlive.
Try returning the average of dict_in[key] and, if this does not work or if
key is None, return average of whole dict.
Parameters
----------
dict_in: dict
Values should be arrays.
key: str
Returns
-------
average: float | [
"Helper",
"function",
"for",
"plot_run_nlive",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/plots.py#L790-L815 |
ejhigson/nestcheck | nestcheck/data_processing.py | batch_process_data | def batch_process_data(file_roots, **kwargs):
"""Process output from many nested sampling runs in parallel with optional
error handling and caching.
The result can be cached using the 'save_name', 'save' and 'load' kwargs
(by default this is not done). See save_load_result docstring for more
detail... | python | def batch_process_data(file_roots, **kwargs):
"""Process output from many nested sampling runs in parallel with optional
error handling and caching.
The result can be cached using the 'save_name', 'save' and 'load' kwargs
(by default this is not done). See save_load_result docstring for more
detail... | [
"def",
"batch_process_data",
"(",
"file_roots",
",",
"*",
"*",
"kwargs",
")",
":",
"base_dir",
"=",
"kwargs",
".",
"pop",
"(",
"'base_dir'",
",",
"'chains'",
")",
"process_func",
"=",
"kwargs",
".",
"pop",
"(",
"'process_func'",
",",
"process_polychord_run",
... | Process output from many nested sampling runs in parallel with optional
error handling and caching.
The result can be cached using the 'save_name', 'save' and 'load' kwargs
(by default this is not done). See save_load_result docstring for more
details.
Remaining kwargs passed to parallel_utils.par... | [
"Process",
"output",
"from",
"many",
"nested",
"sampling",
"runs",
"in",
"parallel",
"with",
"optional",
"error",
"handling",
"and",
"caching",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/data_processing.py#L103-L169 |
ejhigson/nestcheck | nestcheck/data_processing.py | process_error_helper | def process_error_helper(root, base_dir, process_func, errors_to_handle=(),
**func_kwargs):
"""Wrapper which applies process_func and handles some common errors so one
bad run does not spoil the whole batch.
Useful errors to handle include:
OSError: if you are not sure if all ... | python | def process_error_helper(root, base_dir, process_func, errors_to_handle=(),
**func_kwargs):
"""Wrapper which applies process_func and handles some common errors so one
bad run does not spoil the whole batch.
Useful errors to handle include:
OSError: if you are not sure if all ... | [
"def",
"process_error_helper",
"(",
"root",
",",
"base_dir",
",",
"process_func",
",",
"errors_to_handle",
"=",
"(",
")",
",",
"*",
"*",
"func_kwargs",
")",
":",
"try",
":",
"return",
"process_func",
"(",
"root",
",",
"base_dir",
",",
"*",
"*",
"func_kwarg... | Wrapper which applies process_func and handles some common errors so one
bad run does not spoil the whole batch.
Useful errors to handle include:
OSError: if you are not sure if all the files exist
AssertionError: if some of the many assertions fail for known reasons;
for example is there are occa... | [
"Wrapper",
"which",
"applies",
"process_func",
"and",
"handles",
"some",
"common",
"errors",
"so",
"one",
"bad",
"run",
"does",
"not",
"spoil",
"the",
"whole",
"batch",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/data_processing.py#L172-L209 |
ejhigson/nestcheck | nestcheck/data_processing.py | process_polychord_run | def process_polychord_run(file_root, base_dir, process_stats_file=True,
**kwargs):
"""Loads data from a PolyChord run into the nestcheck dictionary format for
analysis.
N.B. producing required output file containing information about the
iso-likelihood contours within which po... | python | def process_polychord_run(file_root, base_dir, process_stats_file=True,
**kwargs):
"""Loads data from a PolyChord run into the nestcheck dictionary format for
analysis.
N.B. producing required output file containing information about the
iso-likelihood contours within which po... | [
"def",
"process_polychord_run",
"(",
"file_root",
",",
"base_dir",
",",
"process_stats_file",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# N.B. PolyChord dead points files also contains remaining live points at",
"# termination",
"samples",
"=",
"np",
".",
"loadtxt"... | Loads data from a PolyChord run into the nestcheck dictionary format for
analysis.
N.B. producing required output file containing information about the
iso-likelihood contours within which points were sampled (where they were
"born") requies PolyChord version v1.13 or later and the setting
write_de... | [
"Loads",
"data",
"from",
"a",
"PolyChord",
"run",
"into",
"the",
"nestcheck",
"dictionary",
"format",
"for",
"analysis",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/data_processing.py#L212-L254 |
ejhigson/nestcheck | nestcheck/data_processing.py | process_multinest_run | def process_multinest_run(file_root, base_dir, **kwargs):
"""Loads data from a MultiNest run into the nestcheck dictionary format for
analysis.
N.B. producing required output file containing information about the
iso-likelihood contours within which points were sampled (where they were
"born") requ... | python | def process_multinest_run(file_root, base_dir, **kwargs):
"""Loads data from a MultiNest run into the nestcheck dictionary format for
analysis.
N.B. producing required output file containing information about the
iso-likelihood contours within which points were sampled (where they were
"born") requ... | [
"def",
"process_multinest_run",
"(",
"file_root",
",",
"base_dir",
",",
"*",
"*",
"kwargs",
")",
":",
"# Load dead and live points",
"dead",
"=",
"np",
".",
"loadtxt",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base_dir",
",",
"file_root",
")",
"+",
"'-dea... | Loads data from a MultiNest run into the nestcheck dictionary format for
analysis.
N.B. producing required output file containing information about the
iso-likelihood contours within which points were sampled (where they were
"born") requies MultiNest version 3.11 or later.
Parameters
--------... | [
"Loads",
"data",
"from",
"a",
"MultiNest",
"run",
"into",
"the",
"nestcheck",
"dictionary",
"format",
"for",
"analysis",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/data_processing.py#L257-L299 |
ejhigson/nestcheck | nestcheck/data_processing.py | process_dynesty_run | def process_dynesty_run(results):
"""Transforms results from a dynesty run into the nestcheck dictionary
format for analysis. This function has been tested with dynesty v9.2.0.
Note that the nestcheck point weights and evidence will not be exactly
the same as the dynesty ones as nestcheck calculates lo... | python | def process_dynesty_run(results):
"""Transforms results from a dynesty run into the nestcheck dictionary
format for analysis. This function has been tested with dynesty v9.2.0.
Note that the nestcheck point weights and evidence will not be exactly
the same as the dynesty ones as nestcheck calculates lo... | [
"def",
"process_dynesty_run",
"(",
"results",
")",
":",
"samples",
"=",
"np",
".",
"zeros",
"(",
"(",
"results",
".",
"samples",
".",
"shape",
"[",
"0",
"]",
",",
"results",
".",
"samples",
".",
"shape",
"[",
"1",
"]",
"+",
"3",
")",
")",
"samples"... | Transforms results from a dynesty run into the nestcheck dictionary
format for analysis. This function has been tested with dynesty v9.2.0.
Note that the nestcheck point weights and evidence will not be exactly
the same as the dynesty ones as nestcheck calculates logX volumes more
precisely (using the ... | [
"Transforms",
"results",
"from",
"a",
"dynesty",
"run",
"into",
"the",
"nestcheck",
"dictionary",
"format",
"for",
"analysis",
".",
"This",
"function",
"has",
"been",
"tested",
"with",
"dynesty",
"v9",
".",
"2",
".",
"0",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/data_processing.py#L302-L357 |
ejhigson/nestcheck | nestcheck/data_processing.py | process_polychord_stats | def process_polychord_stats(file_root, base_dir):
"""Reads a PolyChord <root>.stats output file and returns the information
contained in a dictionary.
Parameters
----------
file_root: str
Root for run output file names (PolyChord file_root setting).
base_dir: str
Directory conta... | python | def process_polychord_stats(file_root, base_dir):
"""Reads a PolyChord <root>.stats output file and returns the information
contained in a dictionary.
Parameters
----------
file_root: str
Root for run output file names (PolyChord file_root setting).
base_dir: str
Directory conta... | [
"def",
"process_polychord_stats",
"(",
"file_root",
",",
"base_dir",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base_dir",
",",
"file_root",
")",
"+",
"'.stats'",
"output",
"=",
"{",
"'base_dir'",
":",
"base_dir",
",",
"'file_root'",
... | Reads a PolyChord <root>.stats output file and returns the information
contained in a dictionary.
Parameters
----------
file_root: str
Root for run output file names (PolyChord file_root setting).
base_dir: str
Directory containing data (PolyChord base_dir setting).
Returns
... | [
"Reads",
"a",
"PolyChord",
"<root",
">",
".",
"stats",
"output",
"file",
"and",
"returns",
"the",
"information",
"contained",
"in",
"a",
"dictionary",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/data_processing.py#L360-L415 |
ejhigson/nestcheck | nestcheck/data_processing.py | process_samples_array | def process_samples_array(samples, **kwargs):
"""Convert an array of nested sampling dead and live points of the type
produced by PolyChord and MultiNest into a nestcheck nested sampling run
dictionary.
Parameters
----------
samples: 2d numpy array
Array of dead points and any remaining... | python | def process_samples_array(samples, **kwargs):
"""Convert an array of nested sampling dead and live points of the type
produced by PolyChord and MultiNest into a nestcheck nested sampling run
dictionary.
Parameters
----------
samples: 2d numpy array
Array of dead points and any remaining... | [
"def",
"process_samples_array",
"(",
"samples",
",",
"*",
"*",
"kwargs",
")",
":",
"samples",
"=",
"samples",
"[",
"np",
".",
"argsort",
"(",
"samples",
"[",
":",
",",
"-",
"2",
"]",
")",
"]",
"ns_run",
"=",
"{",
"}",
"ns_run",
"[",
"'logl'",
"]",
... | Convert an array of nested sampling dead and live points of the type
produced by PolyChord and MultiNest into a nestcheck nested sampling run
dictionary.
Parameters
----------
samples: 2d numpy array
Array of dead points and any remaining live points at termination.
Has #parameters ... | [
"Convert",
"an",
"array",
"of",
"nested",
"sampling",
"dead",
"and",
"live",
"points",
"of",
"the",
"type",
"produced",
"by",
"PolyChord",
"and",
"MultiNest",
"into",
"a",
"nestcheck",
"nested",
"sampling",
"run",
"dictionary",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/data_processing.py#L418-L478 |
ejhigson/nestcheck | nestcheck/data_processing.py | birth_inds_given_contours | def birth_inds_given_contours(birth_logl_arr, logl_arr, **kwargs):
"""Maps the iso-likelihood contours on which points were born to the
index of the dead point on this contour.
MultiNest and PolyChord use different values to identify the inital live
points which were sampled from the whole prior (PolyC... | python | def birth_inds_given_contours(birth_logl_arr, logl_arr, **kwargs):
"""Maps the iso-likelihood contours on which points were born to the
index of the dead point on this contour.
MultiNest and PolyChord use different values to identify the inital live
points which were sampled from the whole prior (PolyC... | [
"def",
"birth_inds_given_contours",
"(",
"birth_logl_arr",
",",
"logl_arr",
",",
"*",
"*",
"kwargs",
")",
":",
"dup_assert",
"=",
"kwargs",
".",
"pop",
"(",
"'dup_assert'",
",",
"False",
")",
"dup_warn",
"=",
"kwargs",
".",
"pop",
"(",
"'dup_warn'",
",",
"... | Maps the iso-likelihood contours on which points were born to the
index of the dead point on this contour.
MultiNest and PolyChord use different values to identify the inital live
points which were sampled from the whole prior (PolyChord uses -1e+30
and MultiNest -0.179769313486231571E+309). However in... | [
"Maps",
"the",
"iso",
"-",
"likelihood",
"contours",
"on",
"which",
"points",
"were",
"born",
"to",
"the",
"index",
"of",
"the",
"dead",
"point",
"on",
"this",
"contour",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/data_processing.py#L481-L591 |
ejhigson/nestcheck | nestcheck/data_processing.py | sample_less_than_condition | def sample_less_than_condition(choices_in, condition):
"""Creates a random sample from choices without replacement, subject to the
condition that each element of the output is greater than the corresponding
element of the condition array.
condition should be in ascending order.
"""
output = np.... | python | def sample_less_than_condition(choices_in, condition):
"""Creates a random sample from choices without replacement, subject to the
condition that each element of the output is greater than the corresponding
element of the condition array.
condition should be in ascending order.
"""
output = np.... | [
"def",
"sample_less_than_condition",
"(",
"choices_in",
",",
"condition",
")",
":",
"output",
"=",
"np",
".",
"zeros",
"(",
"min",
"(",
"condition",
".",
"shape",
"[",
"0",
"]",
",",
"choices_in",
".",
"shape",
"[",
"0",
"]",
")",
")",
"choices",
"=",
... | Creates a random sample from choices without replacement, subject to the
condition that each element of the output is greater than the corresponding
element of the condition array.
condition should be in ascending order. | [
"Creates",
"a",
"random",
"sample",
"from",
"choices",
"without",
"replacement",
"subject",
"to",
"the",
"condition",
"that",
"each",
"element",
"of",
"the",
"output",
"is",
"greater",
"than",
"the",
"corresponding",
"element",
"of",
"the",
"condition",
"array",... | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/data_processing.py#L594-L610 |
ejhigson/nestcheck | nestcheck/data_processing.py | threads_given_birth_inds | def threads_given_birth_inds(birth_inds):
"""Divides a nested sampling run into threads, using info on the indexes
at which points were sampled. See "Sampling errors in nested sampling
parameter estimation" (Higson et al. 2018) for more information.
Parameters
----------
birth_inds: 1d numpy ar... | python | def threads_given_birth_inds(birth_inds):
"""Divides a nested sampling run into threads, using info on the indexes
at which points were sampled. See "Sampling errors in nested sampling
parameter estimation" (Higson et al. 2018) for more information.
Parameters
----------
birth_inds: 1d numpy ar... | [
"def",
"threads_given_birth_inds",
"(",
"birth_inds",
")",
":",
"unique",
",",
"counts",
"=",
"np",
".",
"unique",
"(",
"birth_inds",
",",
"return_counts",
"=",
"True",
")",
"# First get a list of all the indexes on which threads start and their",
"# counts. This is every p... | Divides a nested sampling run into threads, using info on the indexes
at which points were sampled. See "Sampling errors in nested sampling
parameter estimation" (Higson et al. 2018) for more information.
Parameters
----------
birth_inds: 1d numpy array
Indexes of the iso-likelihood contour... | [
"Divides",
"a",
"nested",
"sampling",
"run",
"into",
"threads",
"using",
"info",
"on",
"the",
"indexes",
"at",
"which",
"points",
"were",
"sampled",
".",
"See",
"Sampling",
"errors",
"in",
"nested",
"sampling",
"parameter",
"estimation",
"(",
"Higson",
"et",
... | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/data_processing.py#L613-L697 |
ejhigson/nestcheck | nestcheck/parallel_utils.py | parallel_map | def parallel_map(func, *arg_iterable, **kwargs):
"""Apply function to iterable with parallel map, and hence returns
results in order. functools.partial is used to freeze func_pre_args and
func_kwargs, meaning that the iterable argument must be the last positional
argument.
Roughly equivalent to
... | python | def parallel_map(func, *arg_iterable, **kwargs):
"""Apply function to iterable with parallel map, and hence returns
results in order. functools.partial is used to freeze func_pre_args and
func_kwargs, meaning that the iterable argument must be the last positional
argument.
Roughly equivalent to
... | [
"def",
"parallel_map",
"(",
"func",
",",
"*",
"arg_iterable",
",",
"*",
"*",
"kwargs",
")",
":",
"chunksize",
"=",
"kwargs",
".",
"pop",
"(",
"'chunksize'",
",",
"1",
")",
"func_pre_args",
"=",
"kwargs",
".",
"pop",
"(",
"'func_pre_args'",
",",
"(",
")... | Apply function to iterable with parallel map, and hence returns
results in order. functools.partial is used to freeze func_pre_args and
func_kwargs, meaning that the iterable argument must be the last positional
argument.
Roughly equivalent to
>>> [func(*func_pre_args, x, **func_kwargs) for x in a... | [
"Apply",
"function",
"to",
"iterable",
"with",
"parallel",
"map",
"and",
"hence",
"returns",
"results",
"in",
"order",
".",
"functools",
".",
"partial",
"is",
"used",
"to",
"freeze",
"func_pre_args",
"and",
"func_kwargs",
"meaning",
"that",
"the",
"iterable",
... | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/parallel_utils.py#L12-L67 |
ejhigson/nestcheck | nestcheck/parallel_utils.py | parallel_apply | def parallel_apply(func, arg_iterable, **kwargs):
"""Apply function to iterable with parallelisation and a tqdm progress bar.
Roughly equivalent to
>>> [func(*func_pre_args, x, *func_args, **func_kwargs) for x in
arg_iterable]
but will **not** necessarily return results in input order.
... | python | def parallel_apply(func, arg_iterable, **kwargs):
"""Apply function to iterable with parallelisation and a tqdm progress bar.
Roughly equivalent to
>>> [func(*func_pre_args, x, *func_args, **func_kwargs) for x in
arg_iterable]
but will **not** necessarily return results in input order.
... | [
"def",
"parallel_apply",
"(",
"func",
",",
"arg_iterable",
",",
"*",
"*",
"kwargs",
")",
":",
"max_workers",
"=",
"kwargs",
".",
"pop",
"(",
"'max_workers'",
",",
"None",
")",
"parallel",
"=",
"kwargs",
".",
"pop",
"(",
"'parallel'",
",",
"True",
")",
... | Apply function to iterable with parallelisation and a tqdm progress bar.
Roughly equivalent to
>>> [func(*func_pre_args, x, *func_args, **func_kwargs) for x in
arg_iterable]
but will **not** necessarily return results in input order.
Parameters
----------
func: function
Func... | [
"Apply",
"function",
"to",
"iterable",
"with",
"parallelisation",
"and",
"a",
"tqdm",
"progress",
"bar",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/parallel_utils.py#L70-L142 |
ejhigson/nestcheck | nestcheck/parallel_utils.py | select_tqdm | def select_tqdm():
"""If running in a jupyter notebook, then returns tqdm_notebook.
Otherwise returns a regular tqdm progress bar.
Returns
-------
progress: function
"""
try:
progress = tqdm.tqdm_notebook
assert get_ipython().has_trait('kernel')
except (NameError, Assert... | python | def select_tqdm():
"""If running in a jupyter notebook, then returns tqdm_notebook.
Otherwise returns a regular tqdm progress bar.
Returns
-------
progress: function
"""
try:
progress = tqdm.tqdm_notebook
assert get_ipython().has_trait('kernel')
except (NameError, Assert... | [
"def",
"select_tqdm",
"(",
")",
":",
"try",
":",
"progress",
"=",
"tqdm",
".",
"tqdm_notebook",
"assert",
"get_ipython",
"(",
")",
".",
"has_trait",
"(",
"'kernel'",
")",
"except",
"(",
"NameError",
",",
"AssertionError",
")",
":",
"progress",
"=",
"tqdm",... | If running in a jupyter notebook, then returns tqdm_notebook.
Otherwise returns a regular tqdm progress bar.
Returns
-------
progress: function | [
"If",
"running",
"in",
"a",
"jupyter",
"notebook",
"then",
"returns",
"tqdm_notebook",
".",
"Otherwise",
"returns",
"a",
"regular",
"tqdm",
"progress",
"bar",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/parallel_utils.py#L145-L158 |
ejhigson/nestcheck | nestcheck/pandas_functions.py | summary_df_from_array | def summary_df_from_array(results_array, names, axis=0, **kwargs):
"""Make a panda data frame of the mean and std devs of an array of results,
including the uncertainties on the values.
This function converts the array to a DataFrame and calls summary_df on it.
Parameters
----------
results_ar... | python | def summary_df_from_array(results_array, names, axis=0, **kwargs):
"""Make a panda data frame of the mean and std devs of an array of results,
including the uncertainties on the values.
This function converts the array to a DataFrame and calls summary_df on it.
Parameters
----------
results_ar... | [
"def",
"summary_df_from_array",
"(",
"results_array",
",",
"names",
",",
"axis",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"axis",
"==",
"0",
"or",
"axis",
"==",
"1",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"results_array",
")",
"if",
"a... | Make a panda data frame of the mean and std devs of an array of results,
including the uncertainties on the values.
This function converts the array to a DataFrame and calls summary_df on it.
Parameters
----------
results_array: 2d numpy array
names: list of str
Names for the output df... | [
"Make",
"a",
"panda",
"data",
"frame",
"of",
"the",
"mean",
"and",
"std",
"devs",
"of",
"an",
"array",
"of",
"results",
"including",
"the",
"uncertainties",
"on",
"the",
"values",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/pandas_functions.py#L12-L36 |
ejhigson/nestcheck | nestcheck/pandas_functions.py | summary_df_from_list | def summary_df_from_list(results_list, names, **kwargs):
"""Make a panda data frame of the mean and std devs of each element of a
list of 1d arrays, including the uncertainties on the values.
This just converts the array to a DataFrame and calls summary_df on it.
Parameters
----------
results_... | python | def summary_df_from_list(results_list, names, **kwargs):
"""Make a panda data frame of the mean and std devs of each element of a
list of 1d arrays, including the uncertainties on the values.
This just converts the array to a DataFrame and calls summary_df on it.
Parameters
----------
results_... | [
"def",
"summary_df_from_list",
"(",
"results_list",
",",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"arr",
"in",
"results_list",
":",
"assert",
"arr",
".",
"shape",
"==",
"(",
"len",
"(",
"names",
")",
",",
")",
"df",
"=",
"pd",
".",
"DataFra... | Make a panda data frame of the mean and std devs of each element of a
list of 1d arrays, including the uncertainties on the values.
This just converts the array to a DataFrame and calls summary_df on it.
Parameters
----------
results_list: list of 1d numpy arrays
Must have same length as n... | [
"Make",
"a",
"panda",
"data",
"frame",
"of",
"the",
"mean",
"and",
"std",
"devs",
"of",
"each",
"element",
"of",
"a",
"list",
"of",
"1d",
"arrays",
"including",
"the",
"uncertainties",
"on",
"the",
"values",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/pandas_functions.py#L39-L63 |
ejhigson/nestcheck | nestcheck/pandas_functions.py | summary_df_from_multi | def summary_df_from_multi(multi_in, inds_to_keep=None, **kwargs):
"""Apply summary_df to a multiindex while preserving some levels.
Parameters
----------
multi_in: multiindex pandas DataFrame
inds_to_keep: None or list of strs, optional
Index levels to preserve.
kwargs: dict, optional
... | python | def summary_df_from_multi(multi_in, inds_to_keep=None, **kwargs):
"""Apply summary_df to a multiindex while preserving some levels.
Parameters
----------
multi_in: multiindex pandas DataFrame
inds_to_keep: None or list of strs, optional
Index levels to preserve.
kwargs: dict, optional
... | [
"def",
"summary_df_from_multi",
"(",
"multi_in",
",",
"inds_to_keep",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Need to pop include true values and add separately at the end as",
"# otherwise we get multiple true values added",
"include_true_values",
"=",
"kwargs",
"."... | Apply summary_df to a multiindex while preserving some levels.
Parameters
----------
multi_in: multiindex pandas DataFrame
inds_to_keep: None or list of strs, optional
Index levels to preserve.
kwargs: dict, optional
Keyword arguments to pass to summary_df.
Returns
-------
... | [
"Apply",
"summary_df",
"to",
"a",
"multiindex",
"while",
"preserving",
"some",
"levels",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/pandas_functions.py#L66-L120 |
ejhigson/nestcheck | nestcheck/pandas_functions.py | summary_df | def summary_df(df_in, **kwargs):
"""Make a panda data frame of the mean and std devs of an array of results,
including the uncertainties on the values.
This is similar to pandas.DataFrame.describe but also includes estimates of
the numerical uncertainties.
The output DataFrame has multiindex level... | python | def summary_df(df_in, **kwargs):
"""Make a panda data frame of the mean and std devs of an array of results,
including the uncertainties on the values.
This is similar to pandas.DataFrame.describe but also includes estimates of
the numerical uncertainties.
The output DataFrame has multiindex level... | [
"def",
"summary_df",
"(",
"df_in",
",",
"*",
"*",
"kwargs",
")",
":",
"true_values",
"=",
"kwargs",
".",
"pop",
"(",
"'true_values'",
",",
"None",
")",
"include_true_values",
"=",
"kwargs",
".",
"pop",
"(",
"'include_true_values'",
",",
"False",
")",
"incl... | Make a panda data frame of the mean and std devs of an array of results,
including the uncertainties on the values.
This is similar to pandas.DataFrame.describe but also includes estimates of
the numerical uncertainties.
The output DataFrame has multiindex levels:
'calculation type': mean and st... | [
"Make",
"a",
"panda",
"data",
"frame",
"of",
"the",
"mean",
"and",
"std",
"devs",
"of",
"an",
"array",
"of",
"results",
"including",
"the",
"uncertainties",
"on",
"the",
"values",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/pandas_functions.py#L123-L202 |
ejhigson/nestcheck | nestcheck/pandas_functions.py | efficiency_gain_df | def efficiency_gain_df(method_names, method_values, est_names, **kwargs):
r"""Calculated data frame showing
.. math::
\mathrm{efficiency\,gain}
=
\frac{\mathrm{Var[base\,method]}}{\mathrm{Var[new\,method]}}
See the dynamic nested sampling paper (Higson et al. 2019) for more
de... | python | def efficiency_gain_df(method_names, method_values, est_names, **kwargs):
r"""Calculated data frame showing
.. math::
\mathrm{efficiency\,gain}
=
\frac{\mathrm{Var[base\,method]}}{\mathrm{Var[new\,method]}}
See the dynamic nested sampling paper (Higson et al. 2019) for more
de... | [
"def",
"efficiency_gain_df",
"(",
"method_names",
",",
"method_values",
",",
"est_names",
",",
"*",
"*",
"kwargs",
")",
":",
"true_values",
"=",
"kwargs",
".",
"pop",
"(",
"'true_values'",
",",
"None",
")",
"include_true_values",
"=",
"kwargs",
".",
"pop",
"... | r"""Calculated data frame showing
.. math::
\mathrm{efficiency\,gain}
=
\frac{\mathrm{Var[base\,method]}}{\mathrm{Var[new\,method]}}
See the dynamic nested sampling paper (Higson et al. 2019) for more
details.
The standard method on which to base the gain is assumed to be the... | [
"r",
"Calculated",
"data",
"frame",
"showing"
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/pandas_functions.py#L205-L306 |
ejhigson/nestcheck | nestcheck/pandas_functions.py | paper_format_efficiency_gain_df | def paper_format_efficiency_gain_df(eff_gain_df):
"""Transform efficiency gain data frames output by nestcheck into the
format shown in the dynamic nested sampling paper (Higson et al. 2019).
Parameters
----------
eff_gain_df: pandas DataFrame
DataFrame of the from produced by efficiency_ga... | python | def paper_format_efficiency_gain_df(eff_gain_df):
"""Transform efficiency gain data frames output by nestcheck into the
format shown in the dynamic nested sampling paper (Higson et al. 2019).
Parameters
----------
eff_gain_df: pandas DataFrame
DataFrame of the from produced by efficiency_ga... | [
"def",
"paper_format_efficiency_gain_df",
"(",
"eff_gain_df",
")",
":",
"idxs",
"=",
"pd",
".",
"IndexSlice",
"[",
"[",
"'std'",
",",
"'std efficiency gain'",
"]",
",",
":",
",",
":",
"]",
"paper_df",
"=",
"copy",
".",
"deepcopy",
"(",
"eff_gain_df",
".",
... | Transform efficiency gain data frames output by nestcheck into the
format shown in the dynamic nested sampling paper (Higson et al. 2019).
Parameters
----------
eff_gain_df: pandas DataFrame
DataFrame of the from produced by efficiency_gain_df.
Returns
-------
paper_df: pandas Data... | [
"Transform",
"efficiency",
"gain",
"data",
"frames",
"output",
"by",
"nestcheck",
"into",
"the",
"format",
"shown",
"in",
"the",
"dynamic",
"nested",
"sampling",
"paper",
"(",
"Higson",
"et",
"al",
".",
"2019",
")",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/pandas_functions.py#L309-L345 |
ejhigson/nestcheck | nestcheck/pandas_functions.py | get_eff_gain | def get_eff_gain(base_std, base_std_unc, meth_std, meth_std_unc, adjust=1):
r"""Calculates efficiency gain for a new method compared to a base method.
Given the variation in repeated calculations' results using the two
methods, the efficiency gain is:
.. math::
\mathrm{efficiency\,gain}
... | python | def get_eff_gain(base_std, base_std_unc, meth_std, meth_std_unc, adjust=1):
r"""Calculates efficiency gain for a new method compared to a base method.
Given the variation in repeated calculations' results using the two
methods, the efficiency gain is:
.. math::
\mathrm{efficiency\,gain}
... | [
"def",
"get_eff_gain",
"(",
"base_std",
",",
"base_std_unc",
",",
"meth_std",
",",
"meth_std_unc",
",",
"adjust",
"=",
"1",
")",
":",
"ratio",
"=",
"base_std",
"/",
"meth_std",
"ratio_unc",
"=",
"array_ratio_std",
"(",
"base_std",
",",
"base_std_unc",
",",
"... | r"""Calculates efficiency gain for a new method compared to a base method.
Given the variation in repeated calculations' results using the two
methods, the efficiency gain is:
.. math::
\mathrm{efficiency\,gain}
=
\frac{\mathrm{Var[base\,method]}}{\mathrm{Var[new\,method]}}
Th... | [
"r",
"Calculates",
"efficiency",
"gain",
"for",
"a",
"new",
"method",
"compared",
"to",
"a",
"base",
"method",
".",
"Given",
"the",
"variation",
"in",
"repeated",
"calculations",
"results",
"using",
"the",
"two",
"methods",
"the",
"efficiency",
"gain",
"is",
... | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/pandas_functions.py#L352-L390 |
ejhigson/nestcheck | nestcheck/pandas_functions.py | rmse_and_unc | def rmse_and_unc(values_array, true_values):
r"""Calculate the root meet squared error and its numerical uncertainty.
With a reasonably large number of values in values_list the uncertainty
on sq_errors should be approximately normal (from the central limit
theorem).
Uncertainties are calculated vi... | python | def rmse_and_unc(values_array, true_values):
r"""Calculate the root meet squared error and its numerical uncertainty.
With a reasonably large number of values in values_list the uncertainty
on sq_errors should be approximately normal (from the central limit
theorem).
Uncertainties are calculated vi... | [
"def",
"rmse_and_unc",
"(",
"values_array",
",",
"true_values",
")",
":",
"assert",
"true_values",
".",
"shape",
"==",
"(",
"values_array",
".",
"shape",
"[",
"1",
"]",
",",
")",
"errors",
"=",
"values_array",
"-",
"true_values",
"[",
"np",
".",
"newaxis",... | r"""Calculate the root meet squared error and its numerical uncertainty.
With a reasonably large number of values in values_list the uncertainty
on sq_errors should be approximately normal (from the central limit
theorem).
Uncertainties are calculated via error propagation: if :math:`\sigma`
is the... | [
"r",
"Calculate",
"the",
"root",
"meet",
"squared",
"error",
"and",
"its",
"numerical",
"uncertainty",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/pandas_functions.py#L393-L426 |
ejhigson/nestcheck | nestcheck/pandas_functions.py | array_ratio_std | def array_ratio_std(values_n, sigmas_n, values_d, sigmas_d):
r"""Gives error on the ratio of 2 floats or 2 1-dimensional arrays given
their values and uncertainties. This assumes the covariance = 0, and that
the input uncertainties are small compared to the corresponding input
values. _n and _d denote t... | python | def array_ratio_std(values_n, sigmas_n, values_d, sigmas_d):
r"""Gives error on the ratio of 2 floats or 2 1-dimensional arrays given
their values and uncertainties. This assumes the covariance = 0, and that
the input uncertainties are small compared to the corresponding input
values. _n and _d denote t... | [
"def",
"array_ratio_std",
"(",
"values_n",
",",
"sigmas_n",
",",
"values_d",
",",
"sigmas_d",
")",
":",
"std",
"=",
"np",
".",
"sqrt",
"(",
"(",
"sigmas_n",
"/",
"values_n",
")",
"**",
"2",
"+",
"(",
"sigmas_d",
"/",
"values_d",
")",
"**",
"2",
")",
... | r"""Gives error on the ratio of 2 floats or 2 1-dimensional arrays given
their values and uncertainties. This assumes the covariance = 0, and that
the input uncertainties are small compared to the corresponding input
values. _n and _d denote the numerator and denominator respectively.
Parameters
--... | [
"r",
"Gives",
"error",
"on",
"the",
"ratio",
"of",
"2",
"floats",
"or",
"2",
"1",
"-",
"dimensional",
"arrays",
"given",
"their",
"values",
"and",
"uncertainties",
".",
"This",
"assumes",
"the",
"covariance",
"=",
"0",
"and",
"that",
"the",
"input",
"unc... | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/pandas_functions.py#L429-L453 |
ejhigson/nestcheck | nestcheck/ns_run_utils.py | run_estimators | def run_estimators(ns_run, estimator_list, simulate=False):
"""Calculates values of list of quantities (such as the Bayesian evidence
or mean of parameters) for a single nested sampling run.
Parameters
----------
ns_run: dict
Nested sampling run dict (see data_processing module docstring fo... | python | def run_estimators(ns_run, estimator_list, simulate=False):
"""Calculates values of list of quantities (such as the Bayesian evidence
or mean of parameters) for a single nested sampling run.
Parameters
----------
ns_run: dict
Nested sampling run dict (see data_processing module docstring fo... | [
"def",
"run_estimators",
"(",
"ns_run",
",",
"estimator_list",
",",
"simulate",
"=",
"False",
")",
":",
"logw",
"=",
"get_logw",
"(",
"ns_run",
",",
"simulate",
"=",
"simulate",
")",
"output",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"estimator_list",
"... | Calculates values of list of quantities (such as the Bayesian evidence
or mean of parameters) for a single nested sampling run.
Parameters
----------
ns_run: dict
Nested sampling run dict (see data_processing module docstring for more
details).
estimator_list: list of functions for ... | [
"Calculates",
"values",
"of",
"list",
"of",
"quantities",
"(",
"such",
"as",
"the",
"Bayesian",
"evidence",
"or",
"mean",
"of",
"parameters",
")",
"for",
"a",
"single",
"nested",
"sampling",
"run",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/ns_run_utils.py#L15-L39 |
ejhigson/nestcheck | nestcheck/ns_run_utils.py | array_given_run | def array_given_run(ns_run):
"""Converts information on samples in a nested sampling run dictionary into
a numpy array representation. This allows fast addition of more samples and
recalculation of nlive.
Parameters
----------
ns_run: dict
Nested sampling run dict (see data_processing m... | python | def array_given_run(ns_run):
"""Converts information on samples in a nested sampling run dictionary into
a numpy array representation. This allows fast addition of more samples and
recalculation of nlive.
Parameters
----------
ns_run: dict
Nested sampling run dict (see data_processing m... | [
"def",
"array_given_run",
"(",
"ns_run",
")",
":",
"samples",
"=",
"np",
".",
"zeros",
"(",
"(",
"ns_run",
"[",
"'logl'",
"]",
".",
"shape",
"[",
"0",
"]",
",",
"3",
"+",
"ns_run",
"[",
"'theta'",
"]",
".",
"shape",
"[",
"1",
"]",
")",
")",
"sa... | Converts information on samples in a nested sampling run dictionary into
a numpy array representation. This allows fast addition of more samples and
recalculation of nlive.
Parameters
----------
ns_run: dict
Nested sampling run dict (see data_processing module docstring for more
det... | [
"Converts",
"information",
"on",
"samples",
"in",
"a",
"nested",
"sampling",
"run",
"dictionary",
"into",
"a",
"numpy",
"array",
"representation",
".",
"This",
"allows",
"fast",
"addition",
"of",
"more",
"samples",
"and",
"recalculation",
"of",
"nlive",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/ns_run_utils.py#L42-L67 |
ejhigson/nestcheck | nestcheck/ns_run_utils.py | dict_given_run_array | def dict_given_run_array(samples, thread_min_max):
"""
Converts an array of information about samples back into a nested sampling
run dictionary (see data_processing module docstring for more details).
N.B. the output dict only contains the following keys: 'logl',
'thread_label', 'nlive_array', 'th... | python | def dict_given_run_array(samples, thread_min_max):
"""
Converts an array of information about samples back into a nested sampling
run dictionary (see data_processing module docstring for more details).
N.B. the output dict only contains the following keys: 'logl',
'thread_label', 'nlive_array', 'th... | [
"def",
"dict_given_run_array",
"(",
"samples",
",",
"thread_min_max",
")",
":",
"ns_run",
"=",
"{",
"'logl'",
":",
"samples",
"[",
":",
",",
"0",
"]",
",",
"'thread_labels'",
":",
"samples",
"[",
":",
",",
"1",
"]",
",",
"'thread_min_max'",
":",
"thread_... | Converts an array of information about samples back into a nested sampling
run dictionary (see data_processing module docstring for more details).
N.B. the output dict only contains the following keys: 'logl',
'thread_label', 'nlive_array', 'theta'. Any other keys giving additional
information about th... | [
"Converts",
"an",
"array",
"of",
"information",
"about",
"samples",
"back",
"into",
"a",
"nested",
"sampling",
"run",
"dictionary",
"(",
"see",
"data_processing",
"module",
"docstring",
"for",
"more",
"details",
")",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/ns_run_utils.py#L70-L132 |
ejhigson/nestcheck | nestcheck/ns_run_utils.py | get_run_threads | def get_run_threads(ns_run):
"""
Get the individual threads from a nested sampling run.
Parameters
----------
ns_run: dict
Nested sampling run dict (see data_processing module docstring for more
details).
Returns
-------
threads: list of numpy array
Each thread ... | python | def get_run_threads(ns_run):
"""
Get the individual threads from a nested sampling run.
Parameters
----------
ns_run: dict
Nested sampling run dict (see data_processing module docstring for more
details).
Returns
-------
threads: list of numpy array
Each thread ... | [
"def",
"get_run_threads",
"(",
"ns_run",
")",
":",
"samples",
"=",
"array_given_run",
"(",
"ns_run",
")",
"unique_threads",
"=",
"np",
".",
"unique",
"(",
"ns_run",
"[",
"'thread_labels'",
"]",
")",
"assert",
"ns_run",
"[",
"'thread_min_max'",
"]",
".",
"sha... | Get the individual threads from a nested sampling run.
Parameters
----------
ns_run: dict
Nested sampling run dict (see data_processing module docstring for more
details).
Returns
-------
threads: list of numpy array
Each thread (list element) is a samples array contain... | [
"Get",
"the",
"individual",
"threads",
"from",
"a",
"nested",
"sampling",
"run",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/ns_run_utils.py#L135-L167 |
ejhigson/nestcheck | nestcheck/ns_run_utils.py | combine_ns_runs | def combine_ns_runs(run_list_in, **kwargs):
"""
Combine a list of complete nested sampling run dictionaries into a single
ns run.
Input runs must contain any repeated threads.
Parameters
----------
run_list_in: list of dicts
List of nested sampling runs in dict format (see data_pro... | python | def combine_ns_runs(run_list_in, **kwargs):
"""
Combine a list of complete nested sampling run dictionaries into a single
ns run.
Input runs must contain any repeated threads.
Parameters
----------
run_list_in: list of dicts
List of nested sampling runs in dict format (see data_pro... | [
"def",
"combine_ns_runs",
"(",
"run_list_in",
",",
"*",
"*",
"kwargs",
")",
":",
"run_list",
"=",
"copy",
".",
"deepcopy",
"(",
"run_list_in",
")",
"if",
"len",
"(",
"run_list",
")",
"==",
"1",
":",
"run",
"=",
"run_list",
"[",
"0",
"]",
"else",
":",... | Combine a list of complete nested sampling run dictionaries into a single
ns run.
Input runs must contain any repeated threads.
Parameters
----------
run_list_in: list of dicts
List of nested sampling runs in dict format (see data_processing module
docstring for more details).
... | [
"Combine",
"a",
"list",
"of",
"complete",
"nested",
"sampling",
"run",
"dictionaries",
"into",
"a",
"single",
"ns",
"run",
"."
] | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/ns_run_utils.py#L170-L215 |
ejhigson/nestcheck | nestcheck/ns_run_utils.py | combine_threads | def combine_threads(threads, assert_birth_point=False):
"""
Combine list of threads into a single ns run.
This is different to combining runs as repeated threads are allowed, and as
some threads can start from log-likelihood contours on which no dead
point in the run is present.
Note that if al... | python | def combine_threads(threads, assert_birth_point=False):
"""
Combine list of threads into a single ns run.
This is different to combining runs as repeated threads are allowed, and as
some threads can start from log-likelihood contours on which no dead
point in the run is present.
Note that if al... | [
"def",
"combine_threads",
"(",
"threads",
",",
"assert_birth_point",
"=",
"False",
")",
":",
"thread_min_max",
"=",
"np",
".",
"vstack",
"(",
"[",
"td",
"[",
"'thread_min_max'",
"]",
"for",
"td",
"in",
"threads",
"]",
")",
"assert",
"len",
"(",
"threads",
... | Combine list of threads into a single ns run.
This is different to combining runs as repeated threads are allowed, and as
some threads can start from log-likelihood contours on which no dead
point in the run is present.
Note that if all the thread labels are not unique and in ascending order,
the o... | [
"Combine",
"list",
"of",
"threads",
"into",
"a",
"single",
"ns",
"run",
".",
"This",
"is",
"different",
"to",
"combining",
"runs",
"as",
"repeated",
"threads",
"are",
"allowed",
"and",
"as",
"some",
"threads",
"can",
"start",
"from",
"log",
"-",
"likelihoo... | train | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/ns_run_utils.py#L218-L286 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.