body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
20351f86979df04a233ef27afa571e65b1cc4d58d77e862509ed70201a7bcf37
def _add_video_labels_to_results(self, results, frames_dict, sample_id, label_schema): 'Adds the video labels in ``frames_dict`` to ``results``.\n\n results::\n\n <label_field>: {\n <label_type>: {\n <sample_id>: {\n <frame_id>: {\n <label_id>: <fo.Label>\n }\n or <label - for scalars>\n }\n }\n }\n\n frames_dict::\n\n {\n <frame_id>: {\n <label_field>: {\n <label_type>: [<fo.Label>, ...]\n }\n }\n }\n ' for (frame_id, labels_dict) in frames_dict.items(): attributes = self._gather_classification_attributes(labels_dict, label_schema) results = self._parse_expected_label_fields(results, labels_dict, sample_id, label_schema, attributes, frame_id=frame_id) return results
Adds the video labels in ``frames_dict`` to ``results``. results:: <label_field>: { <label_type>: { <sample_id>: { <frame_id>: { <label_id>: <fo.Label> } or <label - for scalars> } } } frames_dict:: { <frame_id>: { <label_field>: { <label_type>: [<fo.Label>, ...] } } }
fiftyone/utils/labelbox.py
_add_video_labels_to_results
stbdang/fiftyone
3
python
def _add_video_labels_to_results(self, results, frames_dict, sample_id, label_schema): 'Adds the video labels in ``frames_dict`` to ``results``.\n\n results::\n\n <label_field>: {\n <label_type>: {\n <sample_id>: {\n <frame_id>: {\n <label_id>: <fo.Label>\n }\n or <label - for scalars>\n }\n }\n }\n\n frames_dict::\n\n {\n <frame_id>: {\n <label_field>: {\n <label_type>: [<fo.Label>, ...]\n }\n }\n }\n ' for (frame_id, labels_dict) in frames_dict.items(): attributes = self._gather_classification_attributes(labels_dict, label_schema) results = self._parse_expected_label_fields(results, labels_dict, sample_id, label_schema, attributes, frame_id=frame_id) return results
def _add_video_labels_to_results(self, results, frames_dict, sample_id, label_schema): 'Adds the video labels in ``frames_dict`` to ``results``.\n\n results::\n\n <label_field>: {\n <label_type>: {\n <sample_id>: {\n <frame_id>: {\n <label_id>: <fo.Label>\n }\n or <label - for scalars>\n }\n }\n }\n\n frames_dict::\n\n {\n <frame_id>: {\n <label_field>: {\n <label_type>: [<fo.Label>, ...]\n }\n }\n }\n ' for (frame_id, labels_dict) in frames_dict.items(): attributes = self._gather_classification_attributes(labels_dict, label_schema) results = self._parse_expected_label_fields(results, labels_dict, sample_id, label_schema, attributes, frame_id=frame_id) return results<|docstring|>Adds the video labels in ``frames_dict`` to ``results``. results:: <label_field>: { <label_type>: { <sample_id>: { <frame_id>: { <label_id>: <fo.Label> } or <label - for scalars> } } } frames_dict:: { <frame_id>: { <label_field>: { <label_type>: [<fo.Label>, ...] } } }<|endoftext|>
034ada088fe8a97660134d2317af1ad52d31b66c1b2eabbc9ba34810a4c7621d
def load_credentials(self, url=None, api_key=None): 'Load the Labelbox credentials from the given keyword arguments or\n the FiftyOne annotation config.\n\n Args:\n url (None): the url of the Labelbox server\n api_key (None): the Labelbox API key\n ' self._load_config_parameters(url=url, api_key=api_key)
Load the Labelbox credentials from the given keyword arguments or the FiftyOne annotation config. Args: url (None): the url of the Labelbox server api_key (None): the Labelbox API key
fiftyone/utils/labelbox.py
load_credentials
stbdang/fiftyone
3
python
def load_credentials(self, url=None, api_key=None): 'Load the Labelbox credentials from the given keyword arguments or\n the FiftyOne annotation config.\n\n Args:\n url (None): the url of the Labelbox server\n api_key (None): the Labelbox API key\n ' self._load_config_parameters(url=url, api_key=api_key)
def load_credentials(self, url=None, api_key=None): 'Load the Labelbox credentials from the given keyword arguments or\n the FiftyOne annotation config.\n\n Args:\n url (None): the url of the Labelbox server\n api_key (None): the Labelbox API key\n ' self._load_config_parameters(url=url, api_key=api_key)<|docstring|>Load the Labelbox credentials from the given keyword arguments or the FiftyOne annotation config. Args: url (None): the url of the Labelbox server api_key (None): the Labelbox API key<|endoftext|>
ffb32e1eebd14de3e0f53b5134f8d69d9fc8ea831e496ad1bf7fea51c911b3f0
def connect_to_api(self): 'Returns an API instance connected to the Labelbox server.\n\n Returns:\n a :class:`LabelboxAnnotationAPI`\n ' return self._backend.connect_to_api()
Returns an API instance connected to the Labelbox server. Returns: a :class:`LabelboxAnnotationAPI`
fiftyone/utils/labelbox.py
connect_to_api
stbdang/fiftyone
3
python
def connect_to_api(self): 'Returns an API instance connected to the Labelbox server.\n\n Returns:\n a :class:`LabelboxAnnotationAPI`\n ' return self._backend.connect_to_api()
def connect_to_api(self): 'Returns an API instance connected to the Labelbox server.\n\n Returns:\n a :class:`LabelboxAnnotationAPI`\n ' return self._backend.connect_to_api()<|docstring|>Returns an API instance connected to the Labelbox server. Returns: a :class:`LabelboxAnnotationAPI`<|endoftext|>
62248d41d26e77d610158491cc1c05b2127028284c5e268c63d772a92242c53e
def launch_editor(self): 'Launches the Labelbox editor and loads the project for this\n annotation run.\n ' api = self.connect_to_api() project_id = self.project_id editor_url = api.editor_url(project_id) logger.info("Launching editor at '%s'...", editor_url) api.launch_editor(url=editor_url)
Launches the Labelbox editor and loads the project for this annotation run.
fiftyone/utils/labelbox.py
launch_editor
stbdang/fiftyone
3
python
def launch_editor(self): 'Launches the Labelbox editor and loads the project for this\n annotation run.\n ' api = self.connect_to_api() project_id = self.project_id editor_url = api.editor_url(project_id) logger.info("Launching editor at '%s'...", editor_url) api.launch_editor(url=editor_url)
def launch_editor(self): 'Launches the Labelbox editor and loads the project for this\n annotation run.\n ' api = self.connect_to_api() project_id = self.project_id editor_url = api.editor_url(project_id) logger.info("Launching editor at '%s'...", editor_url) api.launch_editor(url=editor_url)<|docstring|>Launches the Labelbox editor and loads the project for this annotation run.<|endoftext|>
10fb839b1ec5a08ee9207dd4e7359f0d6da115ad015214b67391d8b1691cf72c
def get_status(self): 'Gets the status of the annotation run.\n\n Returns:\n a dict of status information\n ' return self._get_status()
Gets the status of the annotation run. Returns: a dict of status information
fiftyone/utils/labelbox.py
get_status
stbdang/fiftyone
3
python
def get_status(self): 'Gets the status of the annotation run.\n\n Returns:\n a dict of status information\n ' return self._get_status()
def get_status(self): 'Gets the status of the annotation run.\n\n Returns:\n a dict of status information\n ' return self._get_status()<|docstring|>Gets the status of the annotation run. Returns: a dict of status information<|endoftext|>
b8f7960d18d6e944b6fa4c040f49e4002563f83fea25d0f7ffbdd0f079c26c28
def print_status(self): 'Prints the status of the annotation run.' self._get_status(log=True)
Prints the status of the annotation run.
fiftyone/utils/labelbox.py
print_status
stbdang/fiftyone
3
python
def print_status(self): self._get_status(log=True)
def print_status(self): self._get_status(log=True)<|docstring|>Prints the status of the annotation run.<|endoftext|>
a921a57011053bcd650648a2f7538be6c98a7ccd37342825fcf27c8a78fa54f8
def cleanup(self): 'Deletes the project associated with this annotation run from the\n Labelbox server.\n ' if (self.project_id is not None): api = self.connect_to_api() api.delete_project(self.project_id) self.project_id = None
Deletes the project associated with this annotation run from the Labelbox server.
fiftyone/utils/labelbox.py
cleanup
stbdang/fiftyone
3
python
def cleanup(self): 'Deletes the project associated with this annotation run from the\n Labelbox server.\n ' if (self.project_id is not None): api = self.connect_to_api() api.delete_project(self.project_id) self.project_id = None
def cleanup(self): 'Deletes the project associated with this annotation run from the\n Labelbox server.\n ' if (self.project_id is not None): api = self.connect_to_api() api.delete_project(self.project_id) self.project_id = None<|docstring|>Deletes the project associated with this annotation run from the Labelbox server.<|endoftext|>
7fcedc0c7a9c670f2700ab28bc78a0ab61a48828b6725431bde07c46cf11f7ce
def best_move(board: list, player: int, depth: int, randn: int) -> int: '\n Get weighted random choice of best n moves\n If there is an immediate winning move, always return it\n ' score_list = load_scores(board, player, depth) heatmap = list(enumerate(score_list)) heatmap.sort(key=(lambda x: x[1]), reverse=True) m_moves = [i[0] for i in heatmap if (i[1] > 0)][:randn] weights = [6, 4, 2, 1, 1][:len(m_moves)] if ((heatmap[0][1] == 10000) or (len(m_moves) <= 1)): return heatmap[0][0] else: return random.choices(m_moves, weights)[0]
Get weighted random choice of best n moves If there is an immediate winning move, always return it
chain_reaction/wrappers/minimax.py
best_move
davidkowalk/chain-reaction-ai
95
python
def best_move(board: list, player: int, depth: int, randn: int) -> int: '\n Get weighted random choice of best n moves\n If there is an immediate winning move, always return it\n ' score_list = load_scores(board, player, depth) heatmap = list(enumerate(score_list)) heatmap.sort(key=(lambda x: x[1]), reverse=True) m_moves = [i[0] for i in heatmap if (i[1] > 0)][:randn] weights = [6, 4, 2, 1, 1][:len(m_moves)] if ((heatmap[0][1] == 10000) or (len(m_moves) <= 1)): return heatmap[0][0] else: return random.choices(m_moves, weights)[0]
def best_move(board: list, player: int, depth: int, randn: int) -> int: '\n Get weighted random choice of best n moves\n If there is an immediate winning move, always return it\n ' score_list = load_scores(board, player, depth) heatmap = list(enumerate(score_list)) heatmap.sort(key=(lambda x: x[1]), reverse=True) m_moves = [i[0] for i in heatmap if (i[1] > 0)][:randn] weights = [6, 4, 2, 1, 1][:len(m_moves)] if ((heatmap[0][1] == 10000) or (len(m_moves) <= 1)): return heatmap[0][0] else: return random.choices(m_moves, weights)[0]<|docstring|>Get weighted random choice of best n moves If there is an immediate winning move, always return it<|endoftext|>
86470a2538157850a6a442d062d685d4420115d9ef9ccc9de6d0bb5af23f887e
@property def line(self): 'Get the line the node occurs on' return (self.module[:self.start].count('\n') + 1)
Get the line the node occurs on
tags/tag.py
line
Alexhuszagh/C-Sublime-Getter-Setters
0
python
@property def line(self): return (self.module[:self.start].count('\n') + 1)
@property def line(self): return (self.module[:self.start].count('\n') + 1)<|docstring|>Get the line the node occurs on<|endoftext|>
7ecd2fbe098b80756ec199497b70f114fb77dab227ad36f440f06fa9b92b712e
@property def indent(self): '\n Get the indentation of the node (indentation type can\n be found via the Sublime API).\n ' indent_newline = self.code.find('\n', (self.open + 1)) if (indent_newline == (- 1)): return previous = self.module[:self.start] newline = previous.rfind('\n') indent = ((self.start - newline) - 1) return indent
Get the indentation of the node (indentation type can be found via the Sublime API).
tags/tag.py
indent
Alexhuszagh/C-Sublime-Getter-Setters
0
python
@property def indent(self): '\n Get the indentation of the node (indentation type can\n be found via the Sublime API).\n ' indent_newline = self.code.find('\n', (self.open + 1)) if (indent_newline == (- 1)): return previous = self.module[:self.start] newline = previous.rfind('\n') indent = ((self.start - newline) - 1) return indent
@property def indent(self): '\n Get the indentation of the node (indentation type can\n be found via the Sublime API).\n ' indent_newline = self.code.find('\n', (self.open + 1)) if (indent_newline == (- 1)): return previous = self.module[:self.start] newline = previous.rfind('\n') indent = ((self.start - newline) - 1) return indent<|docstring|>Get the indentation of the node (indentation type can be found via the Sublime API).<|endoftext|>
1b9093a477275c5305f91f310371e5d36b77f6466d11b28de19148c7eccc8abd
def sort(self): 'Sort tag list'
Sort tag list
tags/tag.py
sort
Alexhuszagh/C-Sublime-Getter-Setters
0
python
def sort(self):
def sort(self): <|docstring|>Sort tag list<|endoftext|>
f2ebe0b63e11820f3ad3b2f3e89caa55d0e52a3a7a8efd6f60c1f203a38cd33f
def __init__(self, vardef, extra_facets=None): 'Initialize fix object.\n\n Parameters\n ----------\n vardef: str\n CMOR table entry\n extra_facets: dict, optional\n Extra facets are mainly used for data outside of the big projects\n like CMIP, CORDEX, obs4MIPs. For details, see :ref:`extra_facets`.\n ' self.vardef = vardef if (extra_facets is None): extra_facets = {} self.extra_facets = extra_facets
Initialize fix object. Parameters ---------- vardef: str CMOR table entry extra_facets: dict, optional Extra facets are mainly used for data outside of the big projects like CMIP, CORDEX, obs4MIPs. For details, see :ref:`extra_facets`.
esmvalcore/cmor/_fixes/fix.py
__init__
jvegasbsc/ESMValCore
26
python
def __init__(self, vardef, extra_facets=None): 'Initialize fix object.\n\n Parameters\n ----------\n vardef: str\n CMOR table entry\n extra_facets: dict, optional\n Extra facets are mainly used for data outside of the big projects\n like CMIP, CORDEX, obs4MIPs. For details, see :ref:`extra_facets`.\n ' self.vardef = vardef if (extra_facets is None): extra_facets = {} self.extra_facets = extra_facets
def __init__(self, vardef, extra_facets=None): 'Initialize fix object.\n\n Parameters\n ----------\n vardef: str\n CMOR table entry\n extra_facets: dict, optional\n Extra facets are mainly used for data outside of the big projects\n like CMIP, CORDEX, obs4MIPs. For details, see :ref:`extra_facets`.\n ' self.vardef = vardef if (extra_facets is None): extra_facets = {} self.extra_facets = extra_facets<|docstring|>Initialize fix object. Parameters ---------- vardef: str CMOR table entry extra_facets: dict, optional Extra facets are mainly used for data outside of the big projects like CMIP, CORDEX, obs4MIPs. For details, see :ref:`extra_facets`.<|endoftext|>
eb81a5203cf6f8eab40ae019c754fd08640639dcc028684421a75d360cd4d563
def fix_file(self, filepath, output_dir): 'Apply fixes to the files prior to creating the cube.\n\n Should be used only to fix errors that prevent loading or can\n not be fixed in the cube (i.e. those related with missing_value\n and _FillValue)\n\n Parameters\n ----------\n filepath: str\n file to fix\n output_dir: str\n path to the folder to store the fixed files, if required\n\n Returns\n -------\n str\n Path to the corrected file. It can be different from the original\n filepath if a fix has been applied, but if not it should be the\n original filepath\n ' return filepath
Apply fixes to the files prior to creating the cube. Should be used only to fix errors that prevent loading or can not be fixed in the cube (i.e. those related with missing_value and _FillValue) Parameters ---------- filepath: str file to fix output_dir: str path to the folder to store the fixed files, if required Returns ------- str Path to the corrected file. It can be different from the original filepath if a fix has been applied, but if not it should be the original filepath
esmvalcore/cmor/_fixes/fix.py
fix_file
jvegasbsc/ESMValCore
26
python
def fix_file(self, filepath, output_dir): 'Apply fixes to the files prior to creating the cube.\n\n Should be used only to fix errors that prevent loading or can\n not be fixed in the cube (i.e. those related with missing_value\n and _FillValue)\n\n Parameters\n ----------\n filepath: str\n file to fix\n output_dir: str\n path to the folder to store the fixed files, if required\n\n Returns\n -------\n str\n Path to the corrected file. It can be different from the original\n filepath if a fix has been applied, but if not it should be the\n original filepath\n ' return filepath
def fix_file(self, filepath, output_dir): 'Apply fixes to the files prior to creating the cube.\n\n Should be used only to fix errors that prevent loading or can\n not be fixed in the cube (i.e. those related with missing_value\n and _FillValue)\n\n Parameters\n ----------\n filepath: str\n file to fix\n output_dir: str\n path to the folder to store the fixed files, if required\n\n Returns\n -------\n str\n Path to the corrected file. It can be different from the original\n filepath if a fix has been applied, but if not it should be the\n original filepath\n ' return filepath<|docstring|>Apply fixes to the files prior to creating the cube. Should be used only to fix errors that prevent loading or can not be fixed in the cube (i.e. those related with missing_value and _FillValue) Parameters ---------- filepath: str file to fix output_dir: str path to the folder to store the fixed files, if required Returns ------- str Path to the corrected file. It can be different from the original filepath if a fix has been applied, but if not it should be the original filepath<|endoftext|>
798961e25936d18308967fd3ab9047ae3c3b774e46c1d52b6d9799d5ea38fda1
def fix_metadata(self, cubes): 'Apply fixes to the metadata of the cube.\n\n Changes applied here must not require data loading.\n\n These fixes should be applied before checking the metadata.\n\n Parameters\n ----------\n cubes: iris.cube.CubeList\n Cubes to fix\n\n Returns\n -------\n iris.cube.CubeList\n Fixed cubes. They can be different instances.\n ' return cubes
Apply fixes to the metadata of the cube. Changes applied here must not require data loading. These fixes should be applied before checking the metadata. Parameters ---------- cubes: iris.cube.CubeList Cubes to fix Returns ------- iris.cube.CubeList Fixed cubes. They can be different instances.
esmvalcore/cmor/_fixes/fix.py
fix_metadata
jvegasbsc/ESMValCore
26
python
def fix_metadata(self, cubes): 'Apply fixes to the metadata of the cube.\n\n Changes applied here must not require data loading.\n\n These fixes should be applied before checking the metadata.\n\n Parameters\n ----------\n cubes: iris.cube.CubeList\n Cubes to fix\n\n Returns\n -------\n iris.cube.CubeList\n Fixed cubes. They can be different instances.\n ' return cubes
def fix_metadata(self, cubes): 'Apply fixes to the metadata of the cube.\n\n Changes applied here must not require data loading.\n\n These fixes should be applied before checking the metadata.\n\n Parameters\n ----------\n cubes: iris.cube.CubeList\n Cubes to fix\n\n Returns\n -------\n iris.cube.CubeList\n Fixed cubes. They can be different instances.\n ' return cubes<|docstring|>Apply fixes to the metadata of the cube. Changes applied here must not require data loading. These fixes should be applied before checking the metadata. Parameters ---------- cubes: iris.cube.CubeList Cubes to fix Returns ------- iris.cube.CubeList Fixed cubes. They can be different instances.<|endoftext|>
bcfa10cf5af1b01615e2b58ccf2ddce0ad7ce557d0b60365ba2bc8cbbe1739fb
def get_cube_from_list(self, cubes, short_name=None): "Get a cube from the list with a given short name.\n\n Parameters\n ----------\n cubes : iris.cube.CubeList\n List of cubes to search\n short_name : str\n Cube's variable short name. If None, short name is the class name\n\n Raises\n ------\n Exception\n If no cube is found\n\n Returns\n -------\n iris.Cube\n Variable's cube\n " if (short_name is None): short_name = self.vardef.short_name for cube in cubes: if (cube.var_name == short_name): return cube raise Exception('Cube for variable "{}" not found'.format(short_name))
Get a cube from the list with a given short name. Parameters ---------- cubes : iris.cube.CubeList List of cubes to search short_name : str Cube's variable short name. If None, short name is the class name Raises ------ Exception If no cube is found Returns ------- iris.Cube Variable's cube
esmvalcore/cmor/_fixes/fix.py
get_cube_from_list
jvegasbsc/ESMValCore
26
python
def get_cube_from_list(self, cubes, short_name=None): "Get a cube from the list with a given short name.\n\n Parameters\n ----------\n cubes : iris.cube.CubeList\n List of cubes to search\n short_name : str\n Cube's variable short name. If None, short name is the class name\n\n Raises\n ------\n Exception\n If no cube is found\n\n Returns\n -------\n iris.Cube\n Variable's cube\n " if (short_name is None): short_name = self.vardef.short_name for cube in cubes: if (cube.var_name == short_name): return cube raise Exception('Cube for variable "{}" not found'.format(short_name))
def get_cube_from_list(self, cubes, short_name=None): "Get a cube from the list with a given short name.\n\n Parameters\n ----------\n cubes : iris.cube.CubeList\n List of cubes to search\n short_name : str\n Cube's variable short name. If None, short name is the class name\n\n Raises\n ------\n Exception\n If no cube is found\n\n Returns\n -------\n iris.Cube\n Variable's cube\n " if (short_name is None): short_name = self.vardef.short_name for cube in cubes: if (cube.var_name == short_name): return cube raise Exception('Cube for variable "{}" not found'.format(short_name))<|docstring|>Get a cube from the list with a given short name. Parameters ---------- cubes : iris.cube.CubeList List of cubes to search short_name : str Cube's variable short name. If None, short name is the class name Raises ------ Exception If no cube is found Returns ------- iris.Cube Variable's cube<|endoftext|>
c7496f0c42db861f6c8ad52df7bf4f83c375946a0f2c80b512730ccdf891571e
def fix_data(self, cube): 'Apply fixes to the data of the cube.\n\n These fixes should be applied before checking the data.\n\n Parameters\n ----------\n cube: iris.cube.Cube\n Cube to fix\n\n Returns\n -------\n iris.cube.Cube\n Fixed cube. It can be a difference instance.\n ' return cube
Apply fixes to the data of the cube. These fixes should be applied before checking the data. Parameters ---------- cube: iris.cube.Cube Cube to fix Returns ------- iris.cube.Cube Fixed cube. It can be a difference instance.
esmvalcore/cmor/_fixes/fix.py
fix_data
jvegasbsc/ESMValCore
26
python
def fix_data(self, cube): 'Apply fixes to the data of the cube.\n\n These fixes should be applied before checking the data.\n\n Parameters\n ----------\n cube: iris.cube.Cube\n Cube to fix\n\n Returns\n -------\n iris.cube.Cube\n Fixed cube. It can be a difference instance.\n ' return cube
def fix_data(self, cube): 'Apply fixes to the data of the cube.\n\n These fixes should be applied before checking the data.\n\n Parameters\n ----------\n cube: iris.cube.Cube\n Cube to fix\n\n Returns\n -------\n iris.cube.Cube\n Fixed cube. It can be a difference instance.\n ' return cube<|docstring|>Apply fixes to the data of the cube. These fixes should be applied before checking the data. Parameters ---------- cube: iris.cube.Cube Cube to fix Returns ------- iris.cube.Cube Fixed cube. It can be a difference instance.<|endoftext|>
8c2e0083bc301889dc11a9d035f59a67d6600ddd98d7eb3acb3e3c5e591f11ca
@staticmethod def get_fixes(project, dataset, mip, short_name, extra_facets=None): "Get the fixes that must be applied for a given dataset.\n\n It will look for them at the module\n esmvalcore.cmor._fixes.PROJECT in the file DATASET, and get\n the classes named allvars (which should be use for fixes that are\n present in all the variables of a dataset, i.e. bad name for the time\n coordinate) and VARIABLE (which should be use for fixes for the\n specific variable).\n\n Project, dataset and variable names will have '-' replaced by '_'\n before checking because it is not possible to use the character '-' in\n python names.\n\n Parameters\n ----------\n project: str\n dataset: str\n mip: str\n short_name: str\n extra_facets: dict, optional\n Extra facets are mainly used for data outside of the big projects\n like CMIP, CORDEX, obs4MIPs. For details, see :ref:`extra_facets`.\n\n Returns\n -------\n list(Fix)\n Fixes to apply for the given data\n " cmor_table = CMOR_TABLES[project] vardef = cmor_table.get_variable(mip, short_name) project = project.replace('-', '_').lower() dataset = dataset.replace('-', '_').lower() short_name = short_name.replace('-', '_').lower() if (extra_facets is None): extra_facets = {} fixes = [] try: fixes_module = importlib.import_module('esmvalcore.cmor._fixes.{0}.{1}'.format(project, dataset)) classes = inspect.getmembers(fixes_module, inspect.isclass) classes = dict(((name.lower(), value) for (name, value) in classes)) for fix_name in (short_name, mip.lower(), 'allvars'): try: fixes.append(classes[fix_name](vardef, extra_facets)) except KeyError: pass except ImportError: pass return fixes
Get the fixes that must be applied for a given dataset. It will look for them at the module esmvalcore.cmor._fixes.PROJECT in the file DATASET, and get the classes named allvars (which should be use for fixes that are present in all the variables of a dataset, i.e. bad name for the time coordinate) and VARIABLE (which should be use for fixes for the specific variable). Project, dataset and variable names will have '-' replaced by '_' before checking because it is not possible to use the character '-' in python names. Parameters ---------- project: str dataset: str mip: str short_name: str extra_facets: dict, optional Extra facets are mainly used for data outside of the big projects like CMIP, CORDEX, obs4MIPs. For details, see :ref:`extra_facets`. Returns ------- list(Fix) Fixes to apply for the given data
esmvalcore/cmor/_fixes/fix.py
get_fixes
jvegasbsc/ESMValCore
26
python
@staticmethod def get_fixes(project, dataset, mip, short_name, extra_facets=None): "Get the fixes that must be applied for a given dataset.\n\n It will look for them at the module\n esmvalcore.cmor._fixes.PROJECT in the file DATASET, and get\n the classes named allvars (which should be use for fixes that are\n present in all the variables of a dataset, i.e. bad name for the time\n coordinate) and VARIABLE (which should be use for fixes for the\n specific variable).\n\n Project, dataset and variable names will have '-' replaced by '_'\n before checking because it is not possible to use the character '-' in\n python names.\n\n Parameters\n ----------\n project: str\n dataset: str\n mip: str\n short_name: str\n extra_facets: dict, optional\n Extra facets are mainly used for data outside of the big projects\n like CMIP, CORDEX, obs4MIPs. For details, see :ref:`extra_facets`.\n\n Returns\n -------\n list(Fix)\n Fixes to apply for the given data\n " cmor_table = CMOR_TABLES[project] vardef = cmor_table.get_variable(mip, short_name) project = project.replace('-', '_').lower() dataset = dataset.replace('-', '_').lower() short_name = short_name.replace('-', '_').lower() if (extra_facets is None): extra_facets = {} fixes = [] try: fixes_module = importlib.import_module('esmvalcore.cmor._fixes.{0}.{1}'.format(project, dataset)) classes = inspect.getmembers(fixes_module, inspect.isclass) classes = dict(((name.lower(), value) for (name, value) in classes)) for fix_name in (short_name, mip.lower(), 'allvars'): try: fixes.append(classes[fix_name](vardef, extra_facets)) except KeyError: pass except ImportError: pass return fixes
@staticmethod def get_fixes(project, dataset, mip, short_name, extra_facets=None): "Get the fixes that must be applied for a given dataset.\n\n It will look for them at the module\n esmvalcore.cmor._fixes.PROJECT in the file DATASET, and get\n the classes named allvars (which should be use for fixes that are\n present in all the variables of a dataset, i.e. bad name for the time\n coordinate) and VARIABLE (which should be use for fixes for the\n specific variable).\n\n Project, dataset and variable names will have '-' replaced by '_'\n before checking because it is not possible to use the character '-' in\n python names.\n\n Parameters\n ----------\n project: str\n dataset: str\n mip: str\n short_name: str\n extra_facets: dict, optional\n Extra facets are mainly used for data outside of the big projects\n like CMIP, CORDEX, obs4MIPs. For details, see :ref:`extra_facets`.\n\n Returns\n -------\n list(Fix)\n Fixes to apply for the given data\n " cmor_table = CMOR_TABLES[project] vardef = cmor_table.get_variable(mip, short_name) project = project.replace('-', '_').lower() dataset = dataset.replace('-', '_').lower() short_name = short_name.replace('-', '_').lower() if (extra_facets is None): extra_facets = {} fixes = [] try: fixes_module = importlib.import_module('esmvalcore.cmor._fixes.{0}.{1}'.format(project, dataset)) classes = inspect.getmembers(fixes_module, inspect.isclass) classes = dict(((name.lower(), value) for (name, value) in classes)) for fix_name in (short_name, mip.lower(), 'allvars'): try: fixes.append(classes[fix_name](vardef, extra_facets)) except KeyError: pass except ImportError: pass return fixes<|docstring|>Get the fixes that must be applied for a given dataset. It will look for them at the module esmvalcore.cmor._fixes.PROJECT in the file DATASET, and get the classes named allvars (which should be use for fixes that are present in all the variables of a dataset, i.e. bad name for the time coordinate) and VARIABLE (which should be use for fixes for the specific variable). Project, dataset and variable names will have '-' replaced by '_' before checking because it is not possible to use the character '-' in python names. Parameters ---------- project: str dataset: str mip: str short_name: str extra_facets: dict, optional Extra facets are mainly used for data outside of the big projects like CMIP, CORDEX, obs4MIPs. For details, see :ref:`extra_facets`. Returns ------- list(Fix) Fixes to apply for the given data<|endoftext|>
2e8f7c77815bf28ea04d6ffeef308e27a09313d830f4b98f7e80ff1768fdc793
@staticmethod def get_fixed_filepath(output_dir, filepath): 'Get the filepath for the fixed file.\n\n Parameters\n ----------\n var_path: str\n Original path\n\n Returns\n -------\n str\n Path to the fixed file\n ' if (not os.path.isdir(output_dir)): os.makedirs(output_dir) return os.path.join(output_dir, os.path.basename(filepath))
Get the filepath for the fixed file. Parameters ---------- var_path: str Original path Returns ------- str Path to the fixed file
esmvalcore/cmor/_fixes/fix.py
get_fixed_filepath
jvegasbsc/ESMValCore
26
python
@staticmethod def get_fixed_filepath(output_dir, filepath): 'Get the filepath for the fixed file.\n\n Parameters\n ----------\n var_path: str\n Original path\n\n Returns\n -------\n str\n Path to the fixed file\n ' if (not os.path.isdir(output_dir)): os.makedirs(output_dir) return os.path.join(output_dir, os.path.basename(filepath))
@staticmethod def get_fixed_filepath(output_dir, filepath): 'Get the filepath for the fixed file.\n\n Parameters\n ----------\n var_path: str\n Original path\n\n Returns\n -------\n str\n Path to the fixed file\n ' if (not os.path.isdir(output_dir)): os.makedirs(output_dir) return os.path.join(output_dir, os.path.basename(filepath))<|docstring|>Get the filepath for the fixed file. Parameters ---------- var_path: str Original path Returns ------- str Path to the fixed file<|endoftext|>
d0d55777b513d5421f075ef619d5beb892dc06c10d75d2d5edc908737a1e75f0
def npm_install(**config): 'Install nodejs packages' npm_executable = config.setdefault('npm_executable', settings.NPM_EXECUTABLE_PATH) npm_workdir = config.setdefault('npm_workdir', settings.NPM_ROOT_PATH) npm_command_args = config.setdefault('npm_command_args', ()) command = shlex.split(npm_executable) if (not npm_command_args): command.extend(['install', ('--prefix=' + settings.NPM_ROOT_PATH)]) else: command.extend(npm_command_args) proc = subprocess.Popen(command, env=os.environ, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, universal_newlines=True, cwd=npm_workdir, bufsize=2048) with StdinWriter(proc): try: while (proc.poll() is None): data = proc.stdout.read(1) if (not data): break print(data, file=sys.stdout, end='') finally: proc.stdout.close() logger.debug(('%s %s' % (proc.poll(), command))) return proc.poll()
Install nodejs packages
npm/finders.py
npm_install
alexsilva/django-npm
0
python
def npm_install(**config): npm_executable = config.setdefault('npm_executable', settings.NPM_EXECUTABLE_PATH) npm_workdir = config.setdefault('npm_workdir', settings.NPM_ROOT_PATH) npm_command_args = config.setdefault('npm_command_args', ()) command = shlex.split(npm_executable) if (not npm_command_args): command.extend(['install', ('--prefix=' + settings.NPM_ROOT_PATH)]) else: command.extend(npm_command_args) proc = subprocess.Popen(command, env=os.environ, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, universal_newlines=True, cwd=npm_workdir, bufsize=2048) with StdinWriter(proc): try: while (proc.poll() is None): data = proc.stdout.read(1) if (not data): break print(data, file=sys.stdout, end=) finally: proc.stdout.close() logger.debug(('%s %s' % (proc.poll(), command))) return proc.poll()
def npm_install(**config): npm_executable = config.setdefault('npm_executable', settings.NPM_EXECUTABLE_PATH) npm_workdir = config.setdefault('npm_workdir', settings.NPM_ROOT_PATH) npm_command_args = config.setdefault('npm_command_args', ()) command = shlex.split(npm_executable) if (not npm_command_args): command.extend(['install', ('--prefix=' + settings.NPM_ROOT_PATH)]) else: command.extend(npm_command_args) proc = subprocess.Popen(command, env=os.environ, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, universal_newlines=True, cwd=npm_workdir, bufsize=2048) with StdinWriter(proc): try: while (proc.poll() is None): data = proc.stdout.read(1) if (not data): break print(data, file=sys.stdout, end=) finally: proc.stdout.close() logger.debug(('%s %s' % (proc.poll(), command))) return proc.poll()<|docstring|>Install nodejs packages<|endoftext|>
f1a3a66ab1496e9dfb0cd51e372c056299ff49917ee62f88d86c20df5f393ec9
def fnmatch_sub(directory, pattern): '\n Match a directory against a potentially longer pattern containing\n wildcards in the path components. fnmatch does the globbing, but there\n appears to be no built-in way to match only the beginning of a pattern.\n ' length = len(directory.split(os.sep)) components = pattern.split(os.sep)[:length] return fnmatch(directory, os.sep.join(components))
Match a directory against a potentially longer pattern containing wildcards in the path components. fnmatch does the globbing, but there appears to be no built-in way to match only the beginning of a pattern.
npm/finders.py
fnmatch_sub
alexsilva/django-npm
0
python
def fnmatch_sub(directory, pattern): '\n Match a directory against a potentially longer pattern containing\n wildcards in the path components. fnmatch does the globbing, but there\n appears to be no built-in way to match only the beginning of a pattern.\n ' length = len(directory.split(os.sep)) components = pattern.split(os.sep)[:length] return fnmatch(directory, os.sep.join(components))
def fnmatch_sub(directory, pattern): '\n Match a directory against a potentially longer pattern containing\n wildcards in the path components. fnmatch does the globbing, but there\n appears to be no built-in way to match only the beginning of a pattern.\n ' length = len(directory.split(os.sep)) components = pattern.split(os.sep)[:length] return fnmatch(directory, os.sep.join(components))<|docstring|>Match a directory against a potentially longer pattern containing wildcards in the path components. fnmatch does the globbing, but there appears to be no built-in way to match only the beginning of a pattern.<|endoftext|>
eb60c2963ae230c122fe3bd5bc83bbbef2c591fe6576e580a37d89e48090f1db
def list(self, ignore_patterns=None): 'List all files in all locations.' if self.cache_enabled: if (self.cached_list is None): self.cached_list = list(self._make_list_generator(ignore_patterns)) return self.cached_list return self._make_list_generator(ignore_patterns)
List all files in all locations.
npm/finders.py
list
alexsilva/django-npm
0
python
def list(self, ignore_patterns=None): if self.cache_enabled: if (self.cached_list is None): self.cached_list = list(self._make_list_generator(ignore_patterns)) return self.cached_list return self._make_list_generator(ignore_patterns)
def list(self, ignore_patterns=None): if self.cache_enabled: if (self.cached_list is None): self.cached_list = list(self._make_list_generator(ignore_patterns)) return self.cached_list return self._make_list_generator(ignore_patterns)<|docstring|>List all files in all locations.<|endoftext|>
2f41255fb83f8804abb905f809da789c85a65785ed2961b69b08bdd5f991bd70
def create_avg_pool(kernel_size, **kwargs): 'Creates an pooling layer.\n\n Note:\n The parameters are configured in\n :attr:`pytorch_layers.Config.avg_pool_kwargs`. These parameters should\n be mutually exclusive from the input ``kwargs``.\n\n Returns:\n torch.nn.Module: The created average pooling layer.\n\n ' config = Config() if (config.dim is Dim.ONE): from torch.nn import AvgPool1d as AvgPool elif (config.dim is Dim.TWO): from torch.nn import AvgPool2d as AvgPool elif (config.dim is Dim.THREE): from torch.nn import AvgPool3d as AvgPool return AvgPool(kernel_size, **config.avg_pool_kwargs, **kwargs)
Creates an pooling layer. Note: The parameters are configured in :attr:`pytorch_layers.Config.avg_pool_kwargs`. These parameters should be mutually exclusive from the input ``kwargs``. Returns: torch.nn.Module: The created average pooling layer.
pytorch_layers/trans.py
create_avg_pool
shuohan/pytorch-layers
0
python
def create_avg_pool(kernel_size, **kwargs): 'Creates an pooling layer.\n\n Note:\n The parameters are configured in\n :attr:`pytorch_layers.Config.avg_pool_kwargs`. These parameters should\n be mutually exclusive from the input ``kwargs``.\n\n Returns:\n torch.nn.Module: The created average pooling layer.\n\n ' config = Config() if (config.dim is Dim.ONE): from torch.nn import AvgPool1d as AvgPool elif (config.dim is Dim.TWO): from torch.nn import AvgPool2d as AvgPool elif (config.dim is Dim.THREE): from torch.nn import AvgPool3d as AvgPool return AvgPool(kernel_size, **config.avg_pool_kwargs, **kwargs)
def create_avg_pool(kernel_size, **kwargs): 'Creates an pooling layer.\n\n Note:\n The parameters are configured in\n :attr:`pytorch_layers.Config.avg_pool_kwargs`. These parameters should\n be mutually exclusive from the input ``kwargs``.\n\n Returns:\n torch.nn.Module: The created average pooling layer.\n\n ' config = Config() if (config.dim is Dim.ONE): from torch.nn import AvgPool1d as AvgPool elif (config.dim is Dim.TWO): from torch.nn import AvgPool2d as AvgPool elif (config.dim is Dim.THREE): from torch.nn import AvgPool3d as AvgPool return AvgPool(kernel_size, **config.avg_pool_kwargs, **kwargs)<|docstring|>Creates an pooling layer. Note: The parameters are configured in :attr:`pytorch_layers.Config.avg_pool_kwargs`. These parameters should be mutually exclusive from the input ``kwargs``. Returns: torch.nn.Module: The created average pooling layer.<|endoftext|>
2812e51216f6807f7e1617e08c5575238ffc66ae98eca71a8cc9bdaa57797cff
def create_two_avg_pool(**kwargs): 'Creates pooling with kernel size 2.' return create_avg_pool(2, **kwargs)
Creates pooling with kernel size 2.
pytorch_layers/trans.py
create_two_avg_pool
shuohan/pytorch-layers
0
python
def create_two_avg_pool(**kwargs): return create_avg_pool(2, **kwargs)
def create_two_avg_pool(**kwargs): return create_avg_pool(2, **kwargs)<|docstring|>Creates pooling with kernel size 2.<|endoftext|>
8fa7486426cb61fa4af83e2315059475409ba4407661edce33cb4e6ad3164c0f
def create_adaptive_avg_pool(output_size): 'Creates adaptive average pooling.\n\n Args:\n output_size (int): The target output size.\n\n Returns:\n torch.nn.Module: The created adaptive average pooling layer.\n\n ' config = Config() if (config.dim is Dim.ONE): from torch.nn import AdaptiveAvgPool1d as AdaptiveAvgPool elif (config.dim is Dim.TWO): from torch.nn import AdaptiveAvgPool2d as AdaptiveAvgPool elif (config.dim is Dim.THREE): from torch.nn import AdaptiveAvgPool3d as AdaptiveAvgPool return AdaptiveAvgPool(output_size)
Creates adaptive average pooling. Args: output_size (int): The target output size. Returns: torch.nn.Module: The created adaptive average pooling layer.
pytorch_layers/trans.py
create_adaptive_avg_pool
shuohan/pytorch-layers
0
python
def create_adaptive_avg_pool(output_size): 'Creates adaptive average pooling.\n\n Args:\n output_size (int): The target output size.\n\n Returns:\n torch.nn.Module: The created adaptive average pooling layer.\n\n ' config = Config() if (config.dim is Dim.ONE): from torch.nn import AdaptiveAvgPool1d as AdaptiveAvgPool elif (config.dim is Dim.TWO): from torch.nn import AdaptiveAvgPool2d as AdaptiveAvgPool elif (config.dim is Dim.THREE): from torch.nn import AdaptiveAvgPool3d as AdaptiveAvgPool return AdaptiveAvgPool(output_size)
def create_adaptive_avg_pool(output_size): 'Creates adaptive average pooling.\n\n Args:\n output_size (int): The target output size.\n\n Returns:\n torch.nn.Module: The created adaptive average pooling layer.\n\n ' config = Config() if (config.dim is Dim.ONE): from torch.nn import AdaptiveAvgPool1d as AdaptiveAvgPool elif (config.dim is Dim.TWO): from torch.nn import AdaptiveAvgPool2d as AdaptiveAvgPool elif (config.dim is Dim.THREE): from torch.nn import AdaptiveAvgPool3d as AdaptiveAvgPool return AdaptiveAvgPool(output_size)<|docstring|>Creates adaptive average pooling. Args: output_size (int): The target output size. Returns: torch.nn.Module: The created adaptive average pooling layer.<|endoftext|>
c85a8359d85cc7d8126c8514172feb69827d0b5410ccadfc784db687aee19329
def create_global_avg_pool(): 'Creates global average pooling.\n\n Average the input image. The kernel size is equal to the image size. The\n output has spatial size 1.\n\n Returns:\n torch.nn.Module: The created pooling layer.\n\n ' return create_adaptive_avg_pool(1)
Creates global average pooling. Average the input image. The kernel size is equal to the image size. The output has spatial size 1. Returns: torch.nn.Module: The created pooling layer.
pytorch_layers/trans.py
create_global_avg_pool
shuohan/pytorch-layers
0
python
def create_global_avg_pool(): 'Creates global average pooling.\n\n Average the input image. The kernel size is equal to the image size. The\n output has spatial size 1.\n\n Returns:\n torch.nn.Module: The created pooling layer.\n\n ' return create_adaptive_avg_pool(1)
def create_global_avg_pool(): 'Creates global average pooling.\n\n Average the input image. The kernel size is equal to the image size. The\n output has spatial size 1.\n\n Returns:\n torch.nn.Module: The created pooling layer.\n\n ' return create_adaptive_avg_pool(1)<|docstring|>Creates global average pooling. Average the input image. The kernel size is equal to the image size. The output has spatial size 1. Returns: torch.nn.Module: The created pooling layer.<|endoftext|>
44a2c4400c00f4587228fcd36f5a4793564a41a296bc8e5810deb3c189d21221
def create_interp(size=None, scale_factor=None): 'Creates an interpolate layer.\n\n See :func:`torch.nn.functionals.interpolate` for the inputs ``size`` and\n ``scale_factor``.\n\n Note:\n The type and other parameters of interpolate are configured in\n :meth:`pytorch_laayers.Config.interp_mode` and\n :attr:`pytorch_laayers.Config.interp_kwargs`.\n\n Returns:\n torch.nn.Module: The created interpolate layer.\n\n ' config = Config() if (config.interp_mode is InterpMode.LINEAR): if (config.dim is Dim.ONE): mode = 'linear' elif (config.dim is Dim.TWO): mode = 'bilinear' elif (config.dim is Dim.THREE): mode = 'trilinear' elif (config.interp_mode is InterpMode.NEAREST): mode = 'nearest' config.interp_kwargs['align_corners'] = None elif (config.interp_mode is InterpMode.CUBIC): if (config.dim is Dim.ONE): raise NotImplementedError elif (config.dim is Dim.TWO): mode = 'bicubic' elif (config.dim is Dim.THREE): raise NotImplementedError elif (config.interp_mode is InterpMode.AREA): mode = 'area' return Interpolate(size=size, scale_factor=scale_factor, mode=mode, **config.interp_kwargs)
Creates an interpolate layer. See :func:`torch.nn.functionals.interpolate` for the inputs ``size`` and ``scale_factor``. Note: The type and other parameters of interpolate are configured in :meth:`pytorch_laayers.Config.interp_mode` and :attr:`pytorch_laayers.Config.interp_kwargs`. Returns: torch.nn.Module: The created interpolate layer.
pytorch_layers/trans.py
create_interp
shuohan/pytorch-layers
0
python
def create_interp(size=None, scale_factor=None): 'Creates an interpolate layer.\n\n See :func:`torch.nn.functionals.interpolate` for the inputs ``size`` and\n ``scale_factor``.\n\n Note:\n The type and other parameters of interpolate are configured in\n :meth:`pytorch_laayers.Config.interp_mode` and\n :attr:`pytorch_laayers.Config.interp_kwargs`.\n\n Returns:\n torch.nn.Module: The created interpolate layer.\n\n ' config = Config() if (config.interp_mode is InterpMode.LINEAR): if (config.dim is Dim.ONE): mode = 'linear' elif (config.dim is Dim.TWO): mode = 'bilinear' elif (config.dim is Dim.THREE): mode = 'trilinear' elif (config.interp_mode is InterpMode.NEAREST): mode = 'nearest' config.interp_kwargs['align_corners'] = None elif (config.interp_mode is InterpMode.CUBIC): if (config.dim is Dim.ONE): raise NotImplementedError elif (config.dim is Dim.TWO): mode = 'bicubic' elif (config.dim is Dim.THREE): raise NotImplementedError elif (config.interp_mode is InterpMode.AREA): mode = 'area' return Interpolate(size=size, scale_factor=scale_factor, mode=mode, **config.interp_kwargs)
def create_interp(size=None, scale_factor=None): 'Creates an interpolate layer.\n\n See :func:`torch.nn.functionals.interpolate` for the inputs ``size`` and\n ``scale_factor``.\n\n Note:\n The type and other parameters of interpolate are configured in\n :meth:`pytorch_laayers.Config.interp_mode` and\n :attr:`pytorch_laayers.Config.interp_kwargs`.\n\n Returns:\n torch.nn.Module: The created interpolate layer.\n\n ' config = Config() if (config.interp_mode is InterpMode.LINEAR): if (config.dim is Dim.ONE): mode = 'linear' elif (config.dim is Dim.TWO): mode = 'bilinear' elif (config.dim is Dim.THREE): mode = 'trilinear' elif (config.interp_mode is InterpMode.NEAREST): mode = 'nearest' config.interp_kwargs['align_corners'] = None elif (config.interp_mode is InterpMode.CUBIC): if (config.dim is Dim.ONE): raise NotImplementedError elif (config.dim is Dim.TWO): mode = 'bicubic' elif (config.dim is Dim.THREE): raise NotImplementedError elif (config.interp_mode is InterpMode.AREA): mode = 'area' return Interpolate(size=size, scale_factor=scale_factor, mode=mode, **config.interp_kwargs)<|docstring|>Creates an interpolate layer. See :func:`torch.nn.functionals.interpolate` for the inputs ``size`` and ``scale_factor``. Note: The type and other parameters of interpolate are configured in :meth:`pytorch_laayers.Config.interp_mode` and :attr:`pytorch_laayers.Config.interp_kwargs`. Returns: torch.nn.Module: The created interpolate layer.<|endoftext|>
2d685c0c85f963ebcbc8ed58437412fdff60c4559cdc71eef04d16f27fc21942
def create_two_upsample(): 'Creates interpolate with scale factor 2.' return create_interp(scale_factor=2)
Creates interpolate with scale factor 2.
pytorch_layers/trans.py
create_two_upsample
shuohan/pytorch-layers
0
python
def create_two_upsample(): return create_interp(scale_factor=2)
def create_two_upsample(): return create_interp(scale_factor=2)<|docstring|>Creates interpolate with scale factor 2.<|endoftext|>
4d2d0acf7e4ef6900c2f30a4ecc5c5b4120dd49aab1ce0ba5f56a3d6594c2736
def reset_trackers(self): '\n Resets the tracking_indices for new detection phase.\n ' self.tracking_indices = []
Resets the tracking_indices for new detection phase.
core/tracker.py
reset_trackers
kad99kev/Trackable
0
python
def reset_trackers(self): '\n \n ' self.tracking_indices = []
def reset_trackers(self): '\n \n ' self.tracking_indices = []<|docstring|>Resets the tracking_indices for new detection phase.<|endoftext|>
0c07ee33034fa86502bc44b8002386ca818aff52ccd68c75ae92c436bd7b3bcf
def start_tracker(self, index, rgb_frame, box): '\n Starts the tracker for a new trackable objects and adds to tracking_indices.\n ' (start_x, start_y, end_x, end_y) = box t = dlib.correlation_tracker() rect = dlib.rectangle(start_x, start_y, end_x, end_y) t.start_track(rgb_frame, rect) self.tracking_indices.append(index) return t
Starts the tracker for a new trackable objects and adds to tracking_indices.
core/tracker.py
start_tracker
kad99kev/Trackable
0
python
def start_tracker(self, index, rgb_frame, box): '\n \n ' (start_x, start_y, end_x, end_y) = box t = dlib.correlation_tracker() rect = dlib.rectangle(start_x, start_y, end_x, end_y) t.start_track(rgb_frame, rect) self.tracking_indices.append(index) return t
def start_tracker(self, index, rgb_frame, box): '\n \n ' (start_x, start_y, end_x, end_y) = box t = dlib.correlation_tracker() rect = dlib.rectangle(start_x, start_y, end_x, end_y) t.start_track(rgb_frame, rect) self.tracking_indices.append(index) return t<|docstring|>Starts the tracker for a new trackable objects and adds to tracking_indices.<|endoftext|>
866f20fbdac096f0cd1058553635588e56f64f11d2ac4eed9a838192c2debc5c
def update_tracker(self, rgb_frame, index, box): '\n Updates the tracker for an existing trackable object and adds to\n tracking_indices if not tracked previously.\n ' (start_x, start_y, end_x, end_y) = box t = dlib.correlation_tracker() rect = dlib.rectangle(start_x, start_y, end_x, end_y) t.start_track(rgb_frame, rect) if (index not in self.tracking_indices): self.tracking_indices.append(index) return t
Updates the tracker for an existing trackable object and adds to tracking_indices if not tracked previously.
core/tracker.py
update_tracker
kad99kev/Trackable
0
python
def update_tracker(self, rgb_frame, index, box): '\n Updates the tracker for an existing trackable object and adds to\n tracking_indices if not tracked previously.\n ' (start_x, start_y, end_x, end_y) = box t = dlib.correlation_tracker() rect = dlib.rectangle(start_x, start_y, end_x, end_y) t.start_track(rgb_frame, rect) if (index not in self.tracking_indices): self.tracking_indices.append(index) return t
def update_tracker(self, rgb_frame, index, box): '\n Updates the tracker for an existing trackable object and adds to\n tracking_indices if not tracked previously.\n ' (start_x, start_y, end_x, end_y) = box t = dlib.correlation_tracker() rect = dlib.rectangle(start_x, start_y, end_x, end_y) t.start_track(rgb_frame, rect) if (index not in self.tracking_indices): self.tracking_indices.append(index) return t<|docstring|>Updates the tracker for an existing trackable object and adds to tracking_indices if not tracked previously.<|endoftext|>
b9cbbac58d39bb711b3508c7d481862d87128de9173f4d0e1cd7d8a3723d8d55
def track_person(self, frame, rgb_frame, trackables): '\n Performs the main update for the tracking algorithm.\n ' rects = [] for index in self.tracking_indices: if (index not in trackables.keys()): continue trackables[index].tracker.update(rgb_frame) pos = trackables[index].tracker.get_position() (start_x, start_y, end_x, end_y) = (int(pos.left()), int(pos.top()), int(pos.right()), int(pos.bottom())) rects.append((start_x, start_y, end_x, end_y)) trackables[index].update_image(frame.copy(), (start_x, start_y, end_x, end_y)) if (len(rects) == 0): for trkble in trackables.values(): trkble.update_disappeared() if (trkble.get_disappeared() > self.max_disappeared): trkble.set_tracking(False) self.__draw_centroids(frame, trackables) return frame input_centroids = np.zeros((len(rects), 2), dtype='int') for (i, (start_x, start_y, end_x, end_y)) in enumerate(rects): c_X = ((start_x + end_x) // 2) c_Y = ((start_y + end_y) // 2) input_centroids[i] = (c_X, c_Y) obj_centroids = [trkble.get_centroid() for trkble in trackables.values() if (trkble.is_being_tracked() and (trkble.get_centroid() is not None))] obj_ids = [trkble.get_id() for trkble in trackables.values() if trkble.is_being_tracked()] if (len(obj_centroids) == 0): self.__draw_bounding_boxes(frame, rects) return frame D = distance.cdist(obj_centroids, input_centroids) rows = D.min(axis=1).argsort() cols = D.argmin(axis=1)[rows] used_rows = set() used_cols = set() for (row, col) in zip(rows, cols): if ((row in used_rows) or (col in used_cols)): continue used_rows.add(row) used_cols.add(col) unused_rows = set(range(0, D.shape[0])).difference(used_rows) unused_cols = set(range(0, D.shape[1])).difference(used_cols) if (D.shape[0] >= D.shape[1]): for row in unused_rows: obj_id = obj_ids[row] trackables[obj_id].update_disappeared() if (trackables[obj_id].get_disappeared() > self.max_disappeared): trackables[obj_id].set_tracking(False) self.__draw_centroids(frame, trackables) self.__draw_bounding_boxes(frame, rects) return frame
Performs the main update for the tracking algorithm.
core/tracker.py
track_person
kad99kev/Trackable
0
python
def track_person(self, frame, rgb_frame, trackables): '\n \n ' rects = [] for index in self.tracking_indices: if (index not in trackables.keys()): continue trackables[index].tracker.update(rgb_frame) pos = trackables[index].tracker.get_position() (start_x, start_y, end_x, end_y) = (int(pos.left()), int(pos.top()), int(pos.right()), int(pos.bottom())) rects.append((start_x, start_y, end_x, end_y)) trackables[index].update_image(frame.copy(), (start_x, start_y, end_x, end_y)) if (len(rects) == 0): for trkble in trackables.values(): trkble.update_disappeared() if (trkble.get_disappeared() > self.max_disappeared): trkble.set_tracking(False) self.__draw_centroids(frame, trackables) return frame input_centroids = np.zeros((len(rects), 2), dtype='int') for (i, (start_x, start_y, end_x, end_y)) in enumerate(rects): c_X = ((start_x + end_x) // 2) c_Y = ((start_y + end_y) // 2) input_centroids[i] = (c_X, c_Y) obj_centroids = [trkble.get_centroid() for trkble in trackables.values() if (trkble.is_being_tracked() and (trkble.get_centroid() is not None))] obj_ids = [trkble.get_id() for trkble in trackables.values() if trkble.is_being_tracked()] if (len(obj_centroids) == 0): self.__draw_bounding_boxes(frame, rects) return frame D = distance.cdist(obj_centroids, input_centroids) rows = D.min(axis=1).argsort() cols = D.argmin(axis=1)[rows] used_rows = set() used_cols = set() for (row, col) in zip(rows, cols): if ((row in used_rows) or (col in used_cols)): continue used_rows.add(row) used_cols.add(col) unused_rows = set(range(0, D.shape[0])).difference(used_rows) unused_cols = set(range(0, D.shape[1])).difference(used_cols) if (D.shape[0] >= D.shape[1]): for row in unused_rows: obj_id = obj_ids[row] trackables[obj_id].update_disappeared() if (trackables[obj_id].get_disappeared() > self.max_disappeared): trackables[obj_id].set_tracking(False) self.__draw_centroids(frame, trackables) self.__draw_bounding_boxes(frame, rects) return frame
def track_person(self, frame, rgb_frame, trackables): '\n \n ' rects = [] for index in self.tracking_indices: if (index not in trackables.keys()): continue trackables[index].tracker.update(rgb_frame) pos = trackables[index].tracker.get_position() (start_x, start_y, end_x, end_y) = (int(pos.left()), int(pos.top()), int(pos.right()), int(pos.bottom())) rects.append((start_x, start_y, end_x, end_y)) trackables[index].update_image(frame.copy(), (start_x, start_y, end_x, end_y)) if (len(rects) == 0): for trkble in trackables.values(): trkble.update_disappeared() if (trkble.get_disappeared() > self.max_disappeared): trkble.set_tracking(False) self.__draw_centroids(frame, trackables) return frame input_centroids = np.zeros((len(rects), 2), dtype='int') for (i, (start_x, start_y, end_x, end_y)) in enumerate(rects): c_X = ((start_x + end_x) // 2) c_Y = ((start_y + end_y) // 2) input_centroids[i] = (c_X, c_Y) obj_centroids = [trkble.get_centroid() for trkble in trackables.values() if (trkble.is_being_tracked() and (trkble.get_centroid() is not None))] obj_ids = [trkble.get_id() for trkble in trackables.values() if trkble.is_being_tracked()] if (len(obj_centroids) == 0): self.__draw_bounding_boxes(frame, rects) return frame D = distance.cdist(obj_centroids, input_centroids) rows = D.min(axis=1).argsort() cols = D.argmin(axis=1)[rows] used_rows = set() used_cols = set() for (row, col) in zip(rows, cols): if ((row in used_rows) or (col in used_cols)): continue used_rows.add(row) used_cols.add(col) unused_rows = set(range(0, D.shape[0])).difference(used_rows) unused_cols = set(range(0, D.shape[1])).difference(used_cols) if (D.shape[0] >= D.shape[1]): for row in unused_rows: obj_id = obj_ids[row] trackables[obj_id].update_disappeared() if (trackables[obj_id].get_disappeared() > self.max_disappeared): trackables[obj_id].set_tracking(False) self.__draw_centroids(frame, trackables) self.__draw_bounding_boxes(frame, rects) return frame<|docstring|>Performs the main update for the tracking algorithm.<|endoftext|>
65d1af49648667eb023b1eee7ec5a75948a155a758fe0f71b29f3affed7bf2b8
def __draw_centroids(self, frame, trackables): '\n Draws the centroids currently tracked objects.\n ' for index in self.tracking_indices: if (index not in trackables.keys()): continue text = f'ID: {index}' centroid = trackables[index].get_centroid() if (centroid is not None): cv2.putText(frame, text, ((centroid[0] - 10), (centroid[1] - 10)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) cv2.circle(frame, (centroid[0], centroid[1]), 4, (0, 255, 0), (- 1))
Draws the centroids currently tracked objects.
core/tracker.py
__draw_centroids
kad99kev/Trackable
0
python
def __draw_centroids(self, frame, trackables): '\n \n ' for index in self.tracking_indices: if (index not in trackables.keys()): continue text = f'ID: {index}' centroid = trackables[index].get_centroid() if (centroid is not None): cv2.putText(frame, text, ((centroid[0] - 10), (centroid[1] - 10)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) cv2.circle(frame, (centroid[0], centroid[1]), 4, (0, 255, 0), (- 1))
def __draw_centroids(self, frame, trackables): '\n \n ' for index in self.tracking_indices: if (index not in trackables.keys()): continue text = f'ID: {index}' centroid = trackables[index].get_centroid() if (centroid is not None): cv2.putText(frame, text, ((centroid[0] - 10), (centroid[1] - 10)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) cv2.circle(frame, (centroid[0], centroid[1]), 4, (0, 255, 0), (- 1))<|docstring|>Draws the centroids currently tracked objects.<|endoftext|>
2e443ecc9edab39afa825daa678280c753aa3b52086fdc732b5825a4f0fb09b4
def __draw_bounding_boxes(self, frame, rects): '\n Draws the bounding boxes for the currently tracked objects.\n ' for (start_x, start_y, end_x, end_y) in rects: cv2.rectangle(frame, (start_x, start_y), (end_x, end_y), (0, 255, 0), 2)
Draws the bounding boxes for the currently tracked objects.
core/tracker.py
__draw_bounding_boxes
kad99kev/Trackable
0
python
def __draw_bounding_boxes(self, frame, rects): '\n \n ' for (start_x, start_y, end_x, end_y) in rects: cv2.rectangle(frame, (start_x, start_y), (end_x, end_y), (0, 255, 0), 2)
def __draw_bounding_boxes(self, frame, rects): '\n \n ' for (start_x, start_y, end_x, end_y) in rects: cv2.rectangle(frame, (start_x, start_y), (end_x, end_y), (0, 255, 0), 2)<|docstring|>Draws the bounding boxes for the currently tracked objects.<|endoftext|>
b8b3ea273a50427f282ac97bde389dfe741b516668963af1a49709aa13557ad1
def write_input_layer(model_name='sas', layer_name='data', channels='-1', width='-1', height='-1', scale='1.0', offsets=None, std=None, model_type='CNN'): '\n Generate Python code defining a SAS deep learning input layer\n\n Parameters\n ----------\n model_name : string\n Name for deep learning model\n layer_name : string\n Layer name\n channels : string\n number of input channels\n width : string\n image width\n height : string\n image height\n scale : string\n scaling factor to apply to raw image pixel data\n offsets : list\n image channel offsets, these values will be subtracted from the pixels of \n each image channel\n std : list\n image channel standardization, the pixels of each image channel will be divided\n by these values\n model_type : string\n Specifies the deep learning model type (either CNN or RNN)\n\n Returns\n -------\n string\n String representing Python code defining a SAS deep learning input layer\n\n ' if (offsets is None): str_offset = 'None' else: str_offset = repr(offsets) if (std is None): str_std = 'None' else: str_std = repr(std) if (model_type == 'CNN'): out = [(((('def sas_model_gen(s, input_crop_type=None, input_channel_offset=' + str_offset) + ', norm_std = ') + str_std) + ', input_image_size=None):'), ' # quick check for deeplearn actionset', ' actionset_list = s.actionsetinfo().setinfo.actionset.tolist()', ' actionset_list = [item.lower() for item in actionset_list]', ' if "deeplearn" not in actionset_list:s.loadactionset("deeplearn")', ' ', ' # quick error-checking and default setting', ' if (input_crop_type is None):', ' input_crop_type="NONE"', ' else:', ' if (input_crop_type.upper() != "NONE") and (input_crop_type.upper() != "UNIQUE"):', ' raise ValueError("Parameter input_crop_type can only be NONE or UNIQUE")', '', ' if (input_image_size is not None):', ' channels = input_image_size[0]', ' if (len(input_image_size) == 2):', ' height = width = input_image_size[1]', ' elif (len(inputImageSize) == 3):', ' height,width = input_image_size[1:]', ' else:', ' raise ValueError("Parameter input_image_size must be a tuple with two or three entries")', '', ' # instantiate model', ((' s.buildModel(model=dict(name=' + repr(model_name)) + ',replace=True),type="CNN")'), '', ' # input layer', (' nchannels=' + channels), ' if input_channel_offset is None and nchannels==3:', ' print("INFO: Setting channel mean values to ImageNet means")', ' input_channel_offset = [103.939, 116.779, 123.68]', ((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((((' layer=dict( type="input", nchannels=' + channels) + ', width=') + width) + ', height=') + height) + ','), ((' scale = ' + scale) + ', randomcrop=input_crop_type, offsets=input_channel_offset, offsetStd=norm_std))'), ' elif input_channel_offset is not None:', ((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((((' layer=dict( type="input", nchannels=' + channels) + ', width=') + width) + ', height=') + height) + ','), ((' scale = ' + scale) + ', randomcrop=input_crop_type, offsets=input_channel_offset, offsetStd=norm_std))'), ' else:', ((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((((' layer=dict( type="input", nchannels=' + channels) + ', width=') + width) + ', height=') + height) + ','), ((' scale = ' + scale) + ', randomcrop=input_crop_type, offsetStd=norm_std))')] else: out = ['def sas_model_gen(s):', ' # quick check for deeplearn actionset', ' actionset_list = s.actionsetinfo().setinfo.actionset.tolist()', ' actionset_list = [item.lower() for item in actionset_list]', ' if "deeplearn" not in actionset_list:s.loadactionset("deeplearn")', ' ', '', ' # instantiate model', ((' s.buildModel(model=dict(name=' + repr(model_name)) + ',replace=True),type="RNN")'), '', ' # input layer', ((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((' layer=dict( type="input", nchannels=' + channels) + ', width=') + width) + ','), ((' height=' + height) + '))')] return '\n'.join(out)
Generate Python code defining a SAS deep learning input layer Parameters ---------- model_name : string Name for deep learning model layer_name : string Layer name channels : string number of input channels width : string image width height : string image height scale : string scaling factor to apply to raw image pixel data offsets : list image channel offsets, these values will be subtracted from the pixels of each image channel std : list image channel standardization, the pixels of each image channel will be divided by these values model_type : string Specifies the deep learning model type (either CNN or RNN) Returns ------- string String representing Python code defining a SAS deep learning input layer
dlpy/model_conversion/write_sas_code.py
write_input_layer
AIStatistics/python-dlpy
1
python
def write_input_layer(model_name='sas', layer_name='data', channels='-1', width='-1', height='-1', scale='1.0', offsets=None, std=None, model_type='CNN'): '\n Generate Python code defining a SAS deep learning input layer\n\n Parameters\n ----------\n model_name : string\n Name for deep learning model\n layer_name : string\n Layer name\n channels : string\n number of input channels\n width : string\n image width\n height : string\n image height\n scale : string\n scaling factor to apply to raw image pixel data\n offsets : list\n image channel offsets, these values will be subtracted from the pixels of \n each image channel\n std : list\n image channel standardization, the pixels of each image channel will be divided\n by these values\n model_type : string\n Specifies the deep learning model type (either CNN or RNN)\n\n Returns\n -------\n string\n String representing Python code defining a SAS deep learning input layer\n\n ' if (offsets is None): str_offset = 'None' else: str_offset = repr(offsets) if (std is None): str_std = 'None' else: str_std = repr(std) if (model_type == 'CNN'): out = [(((('def sas_model_gen(s, input_crop_type=None, input_channel_offset=' + str_offset) + ', norm_std = ') + str_std) + ', input_image_size=None):'), ' # quick check for deeplearn actionset', ' actionset_list = s.actionsetinfo().setinfo.actionset.tolist()', ' actionset_list = [item.lower() for item in actionset_list]', ' if "deeplearn" not in actionset_list:s.loadactionset("deeplearn")', ' ', ' # quick error-checking and default setting', ' if (input_crop_type is None):', ' input_crop_type="NONE"', ' else:', ' if (input_crop_type.upper() != "NONE") and (input_crop_type.upper() != "UNIQUE"):', ' raise ValueError("Parameter input_crop_type can only be NONE or UNIQUE")', , ' if (input_image_size is not None):', ' channels = input_image_size[0]', ' if (len(input_image_size) == 2):', ' height = width = input_image_size[1]', ' elif (len(inputImageSize) == 3):', ' height,width = input_image_size[1:]', ' else:', ' raise ValueError("Parameter input_image_size must be a tuple with two or three entries")', , ' # instantiate model', ((' s.buildModel(model=dict(name=' + repr(model_name)) + ',replace=True),type="CNN")'), , ' # input layer', (' nchannels=' + channels), ' if input_channel_offset is None and nchannels==3:', ' print("INFO: Setting channel mean values to ImageNet means")', ' input_channel_offset = [103.939, 116.779, 123.68]', ((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((((' layer=dict( type="input", nchannels=' + channels) + ', width=') + width) + ', height=') + height) + ','), ((' scale = ' + scale) + ', randomcrop=input_crop_type, offsets=input_channel_offset, offsetStd=norm_std))'), ' elif input_channel_offset is not None:', ((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((((' layer=dict( type="input", nchannels=' + channels) + ', width=') + width) + ', height=') + height) + ','), ((' scale = ' + scale) + ', randomcrop=input_crop_type, offsets=input_channel_offset, offsetStd=norm_std))'), ' else:', ((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((((' layer=dict( type="input", nchannels=' + channels) + ', width=') + width) + ', height=') + height) + ','), ((' scale = ' + scale) + ', randomcrop=input_crop_type, offsetStd=norm_std))')] else: out = ['def sas_model_gen(s):', ' # quick check for deeplearn actionset', ' actionset_list = s.actionsetinfo().setinfo.actionset.tolist()', ' actionset_list = [item.lower() for item in actionset_list]', ' if "deeplearn" not in actionset_list:s.loadactionset("deeplearn")', ' ', , ' # instantiate model', ((' s.buildModel(model=dict(name=' + repr(model_name)) + ',replace=True),type="RNN")'), , ' # input layer', ((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((' layer=dict( type="input", nchannels=' + channels) + ', width=') + width) + ','), ((' height=' + height) + '))')] return '\n'.join(out)
def write_input_layer(model_name='sas', layer_name='data', channels='-1', width='-1', height='-1', scale='1.0', offsets=None, std=None, model_type='CNN'): '\n Generate Python code defining a SAS deep learning input layer\n\n Parameters\n ----------\n model_name : string\n Name for deep learning model\n layer_name : string\n Layer name\n channels : string\n number of input channels\n width : string\n image width\n height : string\n image height\n scale : string\n scaling factor to apply to raw image pixel data\n offsets : list\n image channel offsets, these values will be subtracted from the pixels of \n each image channel\n std : list\n image channel standardization, the pixels of each image channel will be divided\n by these values\n model_type : string\n Specifies the deep learning model type (either CNN or RNN)\n\n Returns\n -------\n string\n String representing Python code defining a SAS deep learning input layer\n\n ' if (offsets is None): str_offset = 'None' else: str_offset = repr(offsets) if (std is None): str_std = 'None' else: str_std = repr(std) if (model_type == 'CNN'): out = [(((('def sas_model_gen(s, input_crop_type=None, input_channel_offset=' + str_offset) + ', norm_std = ') + str_std) + ', input_image_size=None):'), ' # quick check for deeplearn actionset', ' actionset_list = s.actionsetinfo().setinfo.actionset.tolist()', ' actionset_list = [item.lower() for item in actionset_list]', ' if "deeplearn" not in actionset_list:s.loadactionset("deeplearn")', ' ', ' # quick error-checking and default setting', ' if (input_crop_type is None):', ' input_crop_type="NONE"', ' else:', ' if (input_crop_type.upper() != "NONE") and (input_crop_type.upper() != "UNIQUE"):', ' raise ValueError("Parameter input_crop_type can only be NONE or UNIQUE")', , ' if (input_image_size is not None):', ' channels = input_image_size[0]', ' if (len(input_image_size) == 2):', ' height = width = input_image_size[1]', ' elif (len(inputImageSize) == 3):', ' height,width = input_image_size[1:]', ' else:', ' raise ValueError("Parameter input_image_size must be a tuple with two or three entries")', , ' # instantiate model', ((' s.buildModel(model=dict(name=' + repr(model_name)) + ',replace=True),type="CNN")'), , ' # input layer', (' nchannels=' + channels), ' if input_channel_offset is None and nchannels==3:', ' print("INFO: Setting channel mean values to ImageNet means")', ' input_channel_offset = [103.939, 116.779, 123.68]', ((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((((' layer=dict( type="input", nchannels=' + channels) + ', width=') + width) + ', height=') + height) + ','), ((' scale = ' + scale) + ', randomcrop=input_crop_type, offsets=input_channel_offset, offsetStd=norm_std))'), ' elif input_channel_offset is not None:', ((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((((' layer=dict( type="input", nchannels=' + channels) + ', width=') + width) + ', height=') + height) + ','), ((' scale = ' + scale) + ', randomcrop=input_crop_type, offsets=input_channel_offset, offsetStd=norm_std))'), ' else:', ((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((((' layer=dict( type="input", nchannels=' + channels) + ', width=') + width) + ', height=') + height) + ','), ((' scale = ' + scale) + ', randomcrop=input_crop_type, offsetStd=norm_std))')] else: out = ['def sas_model_gen(s):', ' # quick check for deeplearn actionset', ' actionset_list = s.actionsetinfo().setinfo.actionset.tolist()', ' actionset_list = [item.lower() for item in actionset_list]', ' if "deeplearn" not in actionset_list:s.loadactionset("deeplearn")', ' ', , ' # instantiate model', ((' s.buildModel(model=dict(name=' + repr(model_name)) + ',replace=True),type="RNN")'), , ' # input layer', ((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((' layer=dict( type="input", nchannels=' + channels) + ', width=') + width) + ','), ((' height=' + height) + '))')] return '\n'.join(out)<|docstring|>Generate Python code defining a SAS deep learning input layer Parameters ---------- model_name : string Name for deep learning model layer_name : string Layer name channels : string number of input channels width : string image width height : string image height scale : string scaling factor to apply to raw image pixel data offsets : list image channel offsets, these values will be subtracted from the pixels of each image channel std : list image channel standardization, the pixels of each image channel will be divided by these values model_type : string Specifies the deep learning model type (either CNN or RNN) Returns ------- string String representing Python code defining a SAS deep learning input layer<|endoftext|>
bdfc84b53da0d22e7921e84b33f5b35478198aab29cef85a133f7a2c2d517e1e
def write_convolution_layer(model_name='sas', layer_name='conv', nfilters='-1', width='3', height='3', stride='1', nobias='False', activation='identity', dropout='0', src_layer='none', padding='None', pad_height='None', pad_width='None'): '\n Generate Python code defining a SAS deep learning convolution layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n nfilters : string, optional\n number of output feature maps\n width : string, optional\n image width\n height : string, optional\n image height\n stride : string, optional\n vertical/horizontal step size in pixels\n nobias : string, optional\n omit (True) or retain (False) the bias term\n activation : string, optional\n activation function\n dropout : string, optional\n dropout factor (0 < dropout < 1.0)\n src_layer : string, optional\n source layer(s) for the convolution layer\n padding : string, optional\n symmetric zero padding value\n pad_height : string, optional\n symmetric height zero padding value\n pad_width : string, optional\n symmetric width zero padding value\n\n Returns\n -------\n string\n\n ' if ((pad_height.lower() != 'none') or (pad_width.lower() != 'none')): out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((((' layer=dict(type="convolution", nfilters=' + nfilters) + ', width=') + width) + ', height=') + height) + ','), ((((((((((((' stride=' + stride) + ', nobias=') + nobias) + ', act=') + repr(activation)) + ', dropout=') + dropout) + ', padHeight=') + pad_height) + ', padWidth=') + pad_width) + '),'), ((' srcLayers=' + src_layer) + ')')] else: out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((((' layer=dict(type="convolution", nfilters=' + nfilters) + ', width=') + width) + ', height=') + height) + ','), ((((((((((' stride=' + stride) + ', nobias=') + nobias) + ', act=') + repr(activation)) + ', dropout=') + dropout) + ', pad=') + padding) + '),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)
Generate Python code defining a SAS deep learning convolution layer Parameters ---------- model_name : string, optional Name for deep learning model layer_name : string, optional Layer name nfilters : string, optional number of output feature maps width : string, optional image width height : string, optional image height stride : string, optional vertical/horizontal step size in pixels nobias : string, optional omit (True) or retain (False) the bias term activation : string, optional activation function dropout : string, optional dropout factor (0 < dropout < 1.0) src_layer : string, optional source layer(s) for the convolution layer padding : string, optional symmetric zero padding value pad_height : string, optional symmetric height zero padding value pad_width : string, optional symmetric width zero padding value Returns ------- string
dlpy/model_conversion/write_sas_code.py
write_convolution_layer
AIStatistics/python-dlpy
1
python
def write_convolution_layer(model_name='sas', layer_name='conv', nfilters='-1', width='3', height='3', stride='1', nobias='False', activation='identity', dropout='0', src_layer='none', padding='None', pad_height='None', pad_width='None'): '\n Generate Python code defining a SAS deep learning convolution layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n nfilters : string, optional\n number of output feature maps\n width : string, optional\n image width\n height : string, optional\n image height\n stride : string, optional\n vertical/horizontal step size in pixels\n nobias : string, optional\n omit (True) or retain (False) the bias term\n activation : string, optional\n activation function\n dropout : string, optional\n dropout factor (0 < dropout < 1.0)\n src_layer : string, optional\n source layer(s) for the convolution layer\n padding : string, optional\n symmetric zero padding value\n pad_height : string, optional\n symmetric height zero padding value\n pad_width : string, optional\n symmetric width zero padding value\n\n Returns\n -------\n string\n\n ' if ((pad_height.lower() != 'none') or (pad_width.lower() != 'none')): out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((((' layer=dict(type="convolution", nfilters=' + nfilters) + ', width=') + width) + ', height=') + height) + ','), ((((((((((((' stride=' + stride) + ', nobias=') + nobias) + ', act=') + repr(activation)) + ', dropout=') + dropout) + ', padHeight=') + pad_height) + ', padWidth=') + pad_width) + '),'), ((' srcLayers=' + src_layer) + ')')] else: out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((((' layer=dict(type="convolution", nfilters=' + nfilters) + ', width=') + width) + ', height=') + height) + ','), ((((((((((' stride=' + stride) + ', nobias=') + nobias) + ', act=') + repr(activation)) + ', dropout=') + dropout) + ', pad=') + padding) + '),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)
def write_convolution_layer(model_name='sas', layer_name='conv', nfilters='-1', width='3', height='3', stride='1', nobias='False', activation='identity', dropout='0', src_layer='none', padding='None', pad_height='None', pad_width='None'): '\n Generate Python code defining a SAS deep learning convolution layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n nfilters : string, optional\n number of output feature maps\n width : string, optional\n image width\n height : string, optional\n image height\n stride : string, optional\n vertical/horizontal step size in pixels\n nobias : string, optional\n omit (True) or retain (False) the bias term\n activation : string, optional\n activation function\n dropout : string, optional\n dropout factor (0 < dropout < 1.0)\n src_layer : string, optional\n source layer(s) for the convolution layer\n padding : string, optional\n symmetric zero padding value\n pad_height : string, optional\n symmetric height zero padding value\n pad_width : string, optional\n symmetric width zero padding value\n\n Returns\n -------\n string\n\n ' if ((pad_height.lower() != 'none') or (pad_width.lower() != 'none')): out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((((' layer=dict(type="convolution", nfilters=' + nfilters) + ', width=') + width) + ', height=') + height) + ','), ((((((((((((' stride=' + stride) + ', nobias=') + nobias) + ', act=') + repr(activation)) + ', dropout=') + dropout) + ', padHeight=') + pad_height) + ', padWidth=') + pad_width) + '),'), ((' srcLayers=' + src_layer) + ')')] else: out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((((' layer=dict(type="convolution", nfilters=' + nfilters) + ', width=') + width) + ', height=') + height) + ','), ((((((((((' stride=' + stride) + ', nobias=') + nobias) + ', act=') + repr(activation)) + ', dropout=') + dropout) + ', pad=') + padding) + '),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)<|docstring|>Generate Python code defining a SAS deep learning convolution layer Parameters ---------- model_name : string, optional Name for deep learning model layer_name : string, optional Layer name nfilters : string, optional number of output feature maps width : string, optional image width height : string, optional image height stride : string, optional vertical/horizontal step size in pixels nobias : string, optional omit (True) or retain (False) the bias term activation : string, optional activation function dropout : string, optional dropout factor (0 < dropout < 1.0) src_layer : string, optional source layer(s) for the convolution layer padding : string, optional symmetric zero padding value pad_height : string, optional symmetric height zero padding value pad_width : string, optional symmetric width zero padding value Returns ------- string<|endoftext|>
c2553d645367f502f2ae2d120df994374889e768fccc6118c41f064d578eb531
def write_batch_norm_layer(model_name='sas', layer_name='bn', activation='identity', src_layer='none'): '\n Generate Python code defining a SAS deep learning batch normalization layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n activation : string, optional\n activation function\n src_layer : string, optional\n source layer(s) for the convolution layer\n\n Returns\n -------\n string\n\n ' out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((' layer=dict( type="batchnorm", act=' + repr(activation)) + '),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)
Generate Python code defining a SAS deep learning batch normalization layer Parameters ---------- model_name : string, optional Name for deep learning model layer_name : string, optional Layer name activation : string, optional activation function src_layer : string, optional source layer(s) for the convolution layer Returns ------- string
dlpy/model_conversion/write_sas_code.py
write_batch_norm_layer
AIStatistics/python-dlpy
1
python
def write_batch_norm_layer(model_name='sas', layer_name='bn', activation='identity', src_layer='none'): '\n Generate Python code defining a SAS deep learning batch normalization layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n activation : string, optional\n activation function\n src_layer : string, optional\n source layer(s) for the convolution layer\n\n Returns\n -------\n string\n\n ' out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((' layer=dict( type="batchnorm", act=' + repr(activation)) + '),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)
def write_batch_norm_layer(model_name='sas', layer_name='bn', activation='identity', src_layer='none'): '\n Generate Python code defining a SAS deep learning batch normalization layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n activation : string, optional\n activation function\n src_layer : string, optional\n source layer(s) for the convolution layer\n\n Returns\n -------\n string\n\n ' out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((' layer=dict( type="batchnorm", act=' + repr(activation)) + '),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)<|docstring|>Generate Python code defining a SAS deep learning batch normalization layer Parameters ---------- model_name : string, optional Name for deep learning model layer_name : string, optional Layer name activation : string, optional activation function src_layer : string, optional source layer(s) for the convolution layer Returns ------- string<|endoftext|>
066eb3b9792823ea88aa8bb6089cec698adde8439ef60a3aede13dc13552db57
def write_pooling_layer(model_name='sas', layer_name='pool', width='2', height='2', stride='2', type='max', dropout='0', src_layer='none', padding='None', pad_height='None', pad_width='None'): '\n Generate Python code defining a SAS deep learning pooling layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n width : string, optional\n image width\n height : string, optional\n image height\n stride : string, optional\n vertical/horizontal step size in pixels\n type : string, optional\n pooling type\n dropout : string, optional\n dropout factor (0 < dropout < 1.0)\n src_layer : string, optional\n source layer(s) for the convolution layer\n padding : string, optional\n symmetric zero padding value\n pad_height : string, optional\n symmetric height zero padding value\n pad_width : string, optional\n symmetric width zero padding value\n\n Returns\n -------\n string\n\n ' if ((pad_height.lower() != 'none') or (pad_width.lower() != 'none')): out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((' layer=dict(type="pooling", width=' + width) + ', height=') + height) + ','), ((((((' stride=' + stride) + ', pool=') + repr(type)) + ', dropout=') + dropout) + ','), ((((' padHeight=' + pad_height) + ', padWidth=') + pad_width) + '),'), ((' srcLayers=' + src_layer) + ')')] else: out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((' layer=dict(type="pooling", width=' + width) + ', height=') + height) + ','), ((((((' stride=' + stride) + ', pool=') + repr(type)) + ', dropout=') + dropout) + ','), ((' pad=' + padding) + '),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)
Generate Python code defining a SAS deep learning pooling layer Parameters ---------- model_name : string, optional Name for deep learning model layer_name : string, optional Layer name width : string, optional image width height : string, optional image height stride : string, optional vertical/horizontal step size in pixels type : string, optional pooling type dropout : string, optional dropout factor (0 < dropout < 1.0) src_layer : string, optional source layer(s) for the convolution layer padding : string, optional symmetric zero padding value pad_height : string, optional symmetric height zero padding value pad_width : string, optional symmetric width zero padding value Returns ------- string
dlpy/model_conversion/write_sas_code.py
write_pooling_layer
AIStatistics/python-dlpy
1
python
def write_pooling_layer(model_name='sas', layer_name='pool', width='2', height='2', stride='2', type='max', dropout='0', src_layer='none', padding='None', pad_height='None', pad_width='None'): '\n Generate Python code defining a SAS deep learning pooling layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n width : string, optional\n image width\n height : string, optional\n image height\n stride : string, optional\n vertical/horizontal step size in pixels\n type : string, optional\n pooling type\n dropout : string, optional\n dropout factor (0 < dropout < 1.0)\n src_layer : string, optional\n source layer(s) for the convolution layer\n padding : string, optional\n symmetric zero padding value\n pad_height : string, optional\n symmetric height zero padding value\n pad_width : string, optional\n symmetric width zero padding value\n\n Returns\n -------\n string\n\n ' if ((pad_height.lower() != 'none') or (pad_width.lower() != 'none')): out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((' layer=dict(type="pooling", width=' + width) + ', height=') + height) + ','), ((((((' stride=' + stride) + ', pool=') + repr(type)) + ', dropout=') + dropout) + ','), ((((' padHeight=' + pad_height) + ', padWidth=') + pad_width) + '),'), ((' srcLayers=' + src_layer) + ')')] else: out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((' layer=dict(type="pooling", width=' + width) + ', height=') + height) + ','), ((((((' stride=' + stride) + ', pool=') + repr(type)) + ', dropout=') + dropout) + ','), ((' pad=' + padding) + '),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)
def write_pooling_layer(model_name='sas', layer_name='pool', width='2', height='2', stride='2', type='max', dropout='0', src_layer='none', padding='None', pad_height='None', pad_width='None'): '\n Generate Python code defining a SAS deep learning pooling layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n width : string, optional\n image width\n height : string, optional\n image height\n stride : string, optional\n vertical/horizontal step size in pixels\n type : string, optional\n pooling type\n dropout : string, optional\n dropout factor (0 < dropout < 1.0)\n src_layer : string, optional\n source layer(s) for the convolution layer\n padding : string, optional\n symmetric zero padding value\n pad_height : string, optional\n symmetric height zero padding value\n pad_width : string, optional\n symmetric width zero padding value\n\n Returns\n -------\n string\n\n ' if ((pad_height.lower() != 'none') or (pad_width.lower() != 'none')): out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((' layer=dict(type="pooling", width=' + width) + ', height=') + height) + ','), ((((((' stride=' + stride) + ', pool=') + repr(type)) + ', dropout=') + dropout) + ','), ((((' padHeight=' + pad_height) + ', padWidth=') + pad_width) + '),'), ((' srcLayers=' + src_layer) + ')')] else: out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((' layer=dict(type="pooling", width=' + width) + ', height=') + height) + ','), ((((((' stride=' + stride) + ', pool=') + repr(type)) + ', dropout=') + dropout) + ','), ((' pad=' + padding) + '),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)<|docstring|>Generate Python code defining a SAS deep learning pooling layer Parameters ---------- model_name : string, optional Name for deep learning model layer_name : string, optional Layer name width : string, optional image width height : string, optional image height stride : string, optional vertical/horizontal step size in pixels type : string, optional pooling type dropout : string, optional dropout factor (0 < dropout < 1.0) src_layer : string, optional source layer(s) for the convolution layer padding : string, optional symmetric zero padding value pad_height : string, optional symmetric height zero padding value pad_width : string, optional symmetric width zero padding value Returns ------- string<|endoftext|>
b3112d2782a3d28beb3a9d88fff534c826b0ffb3660b2fd87543f584c490f5ab
def write_residual_layer(model_name='sas', layer_name='residual', activation='identity', src_layer='none'): '\n Generate Python code defining a SAS deep learning residual layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n activation : string, optional\n activation function\n src_layer : string, optional\n source layer(s) for the convolution layer\n\n Returns\n -------\n string\n\n ' out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((' layer=dict( type="residual", act="' + activation) + '"),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)
Generate Python code defining a SAS deep learning residual layer Parameters ---------- model_name : string, optional Name for deep learning model layer_name : string, optional Layer name activation : string, optional activation function src_layer : string, optional source layer(s) for the convolution layer Returns ------- string
dlpy/model_conversion/write_sas_code.py
write_residual_layer
AIStatistics/python-dlpy
1
python
def write_residual_layer(model_name='sas', layer_name='residual', activation='identity', src_layer='none'): '\n Generate Python code defining a SAS deep learning residual layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n activation : string, optional\n activation function\n src_layer : string, optional\n source layer(s) for the convolution layer\n\n Returns\n -------\n string\n\n ' out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((' layer=dict( type="residual", act="' + activation) + '"),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)
def write_residual_layer(model_name='sas', layer_name='residual', activation='identity', src_layer='none'): '\n Generate Python code defining a SAS deep learning residual layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n activation : string, optional\n activation function\n src_layer : string, optional\n source layer(s) for the convolution layer\n\n Returns\n -------\n string\n\n ' out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((' layer=dict( type="residual", act="' + activation) + '"),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)<|docstring|>Generate Python code defining a SAS deep learning residual layer Parameters ---------- model_name : string, optional Name for deep learning model layer_name : string, optional Layer name activation : string, optional activation function src_layer : string, optional source layer(s) for the convolution layer Returns ------- string<|endoftext|>
24fb517aaa949d4a59a44c644544c923f497f505d3143e93cfb4d8f5187af7d1
def write_full_connect_layer(model_name='sas', layer_name='fullconnect', nrof_neurons='-1', nobias='true', activation='identity', type='fullconnect', dropout='0', src_layer='none', ctc_loss=False): '\n Generate Python code defining a SAS deep learning fully connected layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n nrof_neurons : string, optional\n number of output neurons\n nobias : string, optional\n omit (True) or retain (False) the bias term\n activation : string, optional\n activation function\n type : string, optional\n fully connected layer type (fullconnect or output)\n dropout : string, optional\n dropout factor (0 < dropout < 1.0)\n src_layer : string, optional\n source layer(s) for the convolution layer\n ctc_loss : boolean, optional\n specifies whether the CTC loss function is used for \n an output layer\n\n Returns\n -------\n string\n\n ' if (type == 'fullconnect'): out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((' layer=dict(type=' + repr(type)) + ', n=') + nrof_neurons) + ','), ((((((' nobias=' + nobias) + ', act=') + repr(activation)) + ', dropout=') + dropout) + '),'), ((' srcLayers=' + src_layer) + ')')] else: if ctc_loss: loss_error = 'CTC' else: loss_error = 'AUTO' out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((' layer=dict(type=' + repr(type)) + ', n=') + nrof_neurons) + ','), ((((' nobias=' + nobias) + ', act=') + repr(activation)) + ','), ((' error = "' + loss_error) + '"),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)
Generate Python code defining a SAS deep learning fully connected layer Parameters ---------- model_name : string, optional Name for deep learning model layer_name : string, optional Layer name nrof_neurons : string, optional number of output neurons nobias : string, optional omit (True) or retain (False) the bias term activation : string, optional activation function type : string, optional fully connected layer type (fullconnect or output) dropout : string, optional dropout factor (0 < dropout < 1.0) src_layer : string, optional source layer(s) for the convolution layer ctc_loss : boolean, optional specifies whether the CTC loss function is used for an output layer Returns ------- string
dlpy/model_conversion/write_sas_code.py
write_full_connect_layer
AIStatistics/python-dlpy
1
python
def write_full_connect_layer(model_name='sas', layer_name='fullconnect', nrof_neurons='-1', nobias='true', activation='identity', type='fullconnect', dropout='0', src_layer='none', ctc_loss=False): '\n Generate Python code defining a SAS deep learning fully connected layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n nrof_neurons : string, optional\n number of output neurons\n nobias : string, optional\n omit (True) or retain (False) the bias term\n activation : string, optional\n activation function\n type : string, optional\n fully connected layer type (fullconnect or output)\n dropout : string, optional\n dropout factor (0 < dropout < 1.0)\n src_layer : string, optional\n source layer(s) for the convolution layer\n ctc_loss : boolean, optional\n specifies whether the CTC loss function is used for \n an output layer\n\n Returns\n -------\n string\n\n ' if (type == 'fullconnect'): out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((' layer=dict(type=' + repr(type)) + ', n=') + nrof_neurons) + ','), ((((((' nobias=' + nobias) + ', act=') + repr(activation)) + ', dropout=') + dropout) + '),'), ((' srcLayers=' + src_layer) + ')')] else: if ctc_loss: loss_error = 'CTC' else: loss_error = 'AUTO' out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((' layer=dict(type=' + repr(type)) + ', n=') + nrof_neurons) + ','), ((((' nobias=' + nobias) + ', act=') + repr(activation)) + ','), ((' error = "' + loss_error) + '"),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)
def write_full_connect_layer(model_name='sas', layer_name='fullconnect', nrof_neurons='-1', nobias='true', activation='identity', type='fullconnect', dropout='0', src_layer='none', ctc_loss=False): '\n Generate Python code defining a SAS deep learning fully connected layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n nrof_neurons : string, optional\n number of output neurons\n nobias : string, optional\n omit (True) or retain (False) the bias term\n activation : string, optional\n activation function\n type : string, optional\n fully connected layer type (fullconnect or output)\n dropout : string, optional\n dropout factor (0 < dropout < 1.0)\n src_layer : string, optional\n source layer(s) for the convolution layer\n ctc_loss : boolean, optional\n specifies whether the CTC loss function is used for \n an output layer\n\n Returns\n -------\n string\n\n ' if (type == 'fullconnect'): out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((' layer=dict(type=' + repr(type)) + ', n=') + nrof_neurons) + ','), ((((((' nobias=' + nobias) + ', act=') + repr(activation)) + ', dropout=') + dropout) + '),'), ((' srcLayers=' + src_layer) + ')')] else: if ctc_loss: loss_error = 'CTC' else: loss_error = 'AUTO' out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((((' layer=dict(type=' + repr(type)) + ', n=') + nrof_neurons) + ','), ((((' nobias=' + nobias) + ', act=') + repr(activation)) + ','), ((' error = "' + loss_error) + '"),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)<|docstring|>Generate Python code defining a SAS deep learning fully connected layer Parameters ---------- model_name : string, optional Name for deep learning model layer_name : string, optional Layer name nrof_neurons : string, optional number of output neurons nobias : string, optional omit (True) or retain (False) the bias term activation : string, optional activation function type : string, optional fully connected layer type (fullconnect or output) dropout : string, optional dropout factor (0 < dropout < 1.0) src_layer : string, optional source layer(s) for the convolution layer ctc_loss : boolean, optional specifies whether the CTC loss function is used for an output layer Returns ------- string<|endoftext|>
86a6f70188304368b0955cbae59ce710df5e80a8944314c01ffa4f517d640ed4
def write_concatenate_layer(model_name='sas', layer_name='concat', activation='identity', src_layer='none'): '\n Generate Python code defining a SAS deep learning concat layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n activation : string, optional\n activation function\n src_layer : string, optional\n source layer(s) for the concat layer\n\n Returns\n -------\n string\n\n ' out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((' layer=dict( type="concat", act="' + activation) + '"),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)
Generate Python code defining a SAS deep learning concat layer Parameters ---------- model_name : string, optional Name for deep learning model layer_name : string, optional Layer name activation : string, optional activation function src_layer : string, optional source layer(s) for the concat layer Returns ------- string
dlpy/model_conversion/write_sas_code.py
write_concatenate_layer
AIStatistics/python-dlpy
1
python
def write_concatenate_layer(model_name='sas', layer_name='concat', activation='identity', src_layer='none'): '\n Generate Python code defining a SAS deep learning concat layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n activation : string, optional\n activation function\n src_layer : string, optional\n source layer(s) for the concat layer\n\n Returns\n -------\n string\n\n ' out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((' layer=dict( type="concat", act="' + activation) + '"),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)
def write_concatenate_layer(model_name='sas', layer_name='concat', activation='identity', src_layer='none'): '\n Generate Python code defining a SAS deep learning concat layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n activation : string, optional\n activation function\n src_layer : string, optional\n source layer(s) for the concat layer\n\n Returns\n -------\n string\n\n ' out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((' layer=dict( type="concat", act="' + activation) + '"),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)<|docstring|>Generate Python code defining a SAS deep learning concat layer Parameters ---------- model_name : string, optional Name for deep learning model layer_name : string, optional Layer name activation : string, optional activation function src_layer : string, optional source layer(s) for the concat layer Returns ------- string<|endoftext|>
06f20aa9286cb76557e82a42d14cfed41d5b280b12bca102e53540b229d3eb7f
def write_recurrent_layer(model_name='sas', layer_name='recurrent', activation='tanh', src_layer='none', rnn_type='rnn', seq_output='samelength', direction='forward', rnn_size=1, dropout=0.0): "\n Generate Python code defining a SAS deep learning recurrent layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n activation : string, optional\n activation function\n src_layer : string, optional\n source layer(s) for the concat layer\n rnn_type : string, optional\n one of 'rnn', 'lstm', or 'gru'\n seq_output : string, optional\n one of 'samelength' or 'encoding'\n direction : boolean, optional\n indicates whether sequence processing \n performed in forward or reverse direction\n rnn_size : integer\n size of hidden dimension\n dropout : float, optional\n dropout rate, values range from 0.0 to 1.0\n\n Returns\n -------\n string\n\n " out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((' layer=dict(type="recurrent", n=' + str(rnn_size)) + ','), ((((((' rnnType="' + rnn_type) + '", act=') + repr(activation)) + ', dropout=') + str(dropout)) + ','), ((((' outputType = "' + seq_output) + '", reversed=') + repr(direction)) + '),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)
Generate Python code defining a SAS deep learning recurrent layer Parameters ---------- model_name : string, optional Name for deep learning model layer_name : string, optional Layer name activation : string, optional activation function src_layer : string, optional source layer(s) for the concat layer rnn_type : string, optional one of 'rnn', 'lstm', or 'gru' seq_output : string, optional one of 'samelength' or 'encoding' direction : boolean, optional indicates whether sequence processing performed in forward or reverse direction rnn_size : integer size of hidden dimension dropout : float, optional dropout rate, values range from 0.0 to 1.0 Returns ------- string
dlpy/model_conversion/write_sas_code.py
write_recurrent_layer
AIStatistics/python-dlpy
1
python
def write_recurrent_layer(model_name='sas', layer_name='recurrent', activation='tanh', src_layer='none', rnn_type='rnn', seq_output='samelength', direction='forward', rnn_size=1, dropout=0.0): "\n Generate Python code defining a SAS deep learning recurrent layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n activation : string, optional\n activation function\n src_layer : string, optional\n source layer(s) for the concat layer\n rnn_type : string, optional\n one of 'rnn', 'lstm', or 'gru'\n seq_output : string, optional\n one of 'samelength' or 'encoding'\n direction : boolean, optional\n indicates whether sequence processing \n performed in forward or reverse direction\n rnn_size : integer\n size of hidden dimension\n dropout : float, optional\n dropout rate, values range from 0.0 to 1.0\n\n Returns\n -------\n string\n\n " out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((' layer=dict(type="recurrent", n=' + str(rnn_size)) + ','), ((((((' rnnType="' + rnn_type) + '", act=') + repr(activation)) + ', dropout=') + str(dropout)) + ','), ((((' outputType = "' + seq_output) + '", reversed=') + repr(direction)) + '),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)
def write_recurrent_layer(model_name='sas', layer_name='recurrent', activation='tanh', src_layer='none', rnn_type='rnn', seq_output='samelength', direction='forward', rnn_size=1, dropout=0.0): "\n Generate Python code defining a SAS deep learning recurrent layer\n\n Parameters\n ----------\n model_name : string, optional\n Name for deep learning model\n layer_name : string, optional\n Layer name\n activation : string, optional\n activation function\n src_layer : string, optional\n source layer(s) for the concat layer\n rnn_type : string, optional\n one of 'rnn', 'lstm', or 'gru'\n seq_output : string, optional\n one of 'samelength' or 'encoding'\n direction : boolean, optional\n indicates whether sequence processing \n performed in forward or reverse direction\n rnn_size : integer\n size of hidden dimension\n dropout : float, optional\n dropout rate, values range from 0.0 to 1.0\n\n Returns\n -------\n string\n\n " out = [((((' s.addLayer(model=' + repr(model_name)) + ', name=') + repr(layer_name)) + ','), ((' layer=dict(type="recurrent", n=' + str(rnn_size)) + ','), ((((((' rnnType="' + rnn_type) + '", act=') + repr(activation)) + ', dropout=') + str(dropout)) + ','), ((((' outputType = "' + seq_output) + '", reversed=') + repr(direction)) + '),'), ((' srcLayers=' + src_layer) + ')')] return '\n'.join(out)<|docstring|>Generate Python code defining a SAS deep learning recurrent layer Parameters ---------- model_name : string, optional Name for deep learning model layer_name : string, optional Layer name activation : string, optional activation function src_layer : string, optional source layer(s) for the concat layer rnn_type : string, optional one of 'rnn', 'lstm', or 'gru' seq_output : string, optional one of 'samelength' or 'encoding' direction : boolean, optional indicates whether sequence processing performed in forward or reverse direction rnn_size : integer size of hidden dimension dropout : float, optional dropout rate, values range from 0.0 to 1.0 Returns ------- string<|endoftext|>
68ecde653719c6ef5a5129d57c9d130078eba11fc4129932710fd717fedbb1aa
def write_main_entry(model_name): '\n Generate Python code defining the __main__ Python entry point\n\n Parameters\n ----------\n model_name : string\n Name for deep learning model\n\n Returns\n -------\n string\n\n ' return ''
Generate Python code defining the __main__ Python entry point Parameters ---------- model_name : string Name for deep learning model Returns ------- string
dlpy/model_conversion/write_sas_code.py
write_main_entry
AIStatistics/python-dlpy
1
python
def write_main_entry(model_name): '\n Generate Python code defining the __main__ Python entry point\n\n Parameters\n ----------\n model_name : string\n Name for deep learning model\n\n Returns\n -------\n string\n\n ' return
def write_main_entry(model_name): '\n Generate Python code defining the __main__ Python entry point\n\n Parameters\n ----------\n model_name : string\n Name for deep learning model\n\n Returns\n -------\n string\n\n ' return <|docstring|>Generate Python code defining the __main__ Python entry point Parameters ---------- model_name : string Name for deep learning model Returns ------- string<|endoftext|>
0d82478d7d09d7fc18f65d24ba4a9e1f1f50f58028a85be954eedd94cad05fe8
def normalize_numpy(u, axis=0, eps=1e-15): '\n Normalizes the values within the axis in a way that they sum up to 1.\n\n Parameters\n ----------\n u : array\n axis : int\n eps : float\n Threshold for the alpha values\n\n Returns\n -------\n * array\n Normalized version of the given matrix\n\n * array(seq_len, n_hidden) :\n The values of the normalizer\n ' u = np.where((u == 0), 0, np.where((u < eps), eps, u)) c = u.sum(axis=axis) c = np.where((c == 0), 1, c) return ((u / c), c)
Normalizes the values within the axis in a way that they sum up to 1. Parameters ---------- u : array axis : int eps : float Threshold for the alpha values Returns ------- * array Normalized version of the given matrix * array(seq_len, n_hidden) : The values of the normalizer
jsl/hmm/hmm_numpy_lib.py
normalize_numpy
probml/JSL
23
python
def normalize_numpy(u, axis=0, eps=1e-15): '\n Normalizes the values within the axis in a way that they sum up to 1.\n\n Parameters\n ----------\n u : array\n axis : int\n eps : float\n Threshold for the alpha values\n\n Returns\n -------\n * array\n Normalized version of the given matrix\n\n * array(seq_len, n_hidden) :\n The values of the normalizer\n ' u = np.where((u == 0), 0, np.where((u < eps), eps, u)) c = u.sum(axis=axis) c = np.where((c == 0), 1, c) return ((u / c), c)
def normalize_numpy(u, axis=0, eps=1e-15): '\n Normalizes the values within the axis in a way that they sum up to 1.\n\n Parameters\n ----------\n u : array\n axis : int\n eps : float\n Threshold for the alpha values\n\n Returns\n -------\n * array\n Normalized version of the given matrix\n\n * array(seq_len, n_hidden) :\n The values of the normalizer\n ' u = np.where((u == 0), 0, np.where((u < eps), eps, u)) c = u.sum(axis=axis) c = np.where((c == 0), 1, c) return ((u / c), c)<|docstring|>Normalizes the values within the axis in a way that they sum up to 1. Parameters ---------- u : array axis : int eps : float Threshold for the alpha values Returns ------- * array Normalized version of the given matrix * array(seq_len, n_hidden) : The values of the normalizer<|endoftext|>
e3c8e7aaba0107e6048fde7f8b23053fe5ac053e436b88be499d0b54503e13d1
def hmm_sample_numpy(params, seq_len, random_state=0): '\n Samples an observation of given length according to the defined\n hidden markov model and gives the sequence of the hidden states\n as well as the observation.\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n seq_len: array(seq_len)\n The length of the observation sequence\n\n random_state : int\n Seed value\n\n Returns\n -------\n * array(seq_len,)\n Hidden state sequence\n\n * array(seq_len,) :\n Observation sequence\n ' def sample_one_step_(hist, a, p): x_t = np.random.choice(a=a, p=p) return (np.append(hist, [x_t]), x_t) seed(random_state) (trans_mat, obs_mat, init_dist) = (params.trans_mat, params.obs_mat, params.init_dist) (n_states, n_obs) = obs_mat.shape state_seq = np.array([], dtype=int) obs_seq = np.array([], dtype=int) latent_states = np.arange(n_states) obs_states = np.arange(n_obs) (state_seq, zt) = sample_one_step_(state_seq, latent_states, init_dist) (obs_seq, xt) = sample_one_step_(obs_seq, obs_states, obs_mat[zt]) for _ in range(1, seq_len): (state_seq, zt) = sample_one_step_(state_seq, latent_states, trans_mat[zt]) (obs_seq, xt) = sample_one_step_(obs_seq, obs_states, obs_mat[zt]) return (state_seq, obs_seq)
Samples an observation of given length according to the defined hidden markov model and gives the sequence of the hidden states as well as the observation. Parameters ---------- params : HMMNumpy Hidden Markov Model seq_len: array(seq_len) The length of the observation sequence random_state : int Seed value Returns ------- * array(seq_len,) Hidden state sequence * array(seq_len,) : Observation sequence
jsl/hmm/hmm_numpy_lib.py
hmm_sample_numpy
probml/JSL
23
python
def hmm_sample_numpy(params, seq_len, random_state=0): '\n Samples an observation of given length according to the defined\n hidden markov model and gives the sequence of the hidden states\n as well as the observation.\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n seq_len: array(seq_len)\n The length of the observation sequence\n\n random_state : int\n Seed value\n\n Returns\n -------\n * array(seq_len,)\n Hidden state sequence\n\n * array(seq_len,) :\n Observation sequence\n ' def sample_one_step_(hist, a, p): x_t = np.random.choice(a=a, p=p) return (np.append(hist, [x_t]), x_t) seed(random_state) (trans_mat, obs_mat, init_dist) = (params.trans_mat, params.obs_mat, params.init_dist) (n_states, n_obs) = obs_mat.shape state_seq = np.array([], dtype=int) obs_seq = np.array([], dtype=int) latent_states = np.arange(n_states) obs_states = np.arange(n_obs) (state_seq, zt) = sample_one_step_(state_seq, latent_states, init_dist) (obs_seq, xt) = sample_one_step_(obs_seq, obs_states, obs_mat[zt]) for _ in range(1, seq_len): (state_seq, zt) = sample_one_step_(state_seq, latent_states, trans_mat[zt]) (obs_seq, xt) = sample_one_step_(obs_seq, obs_states, obs_mat[zt]) return (state_seq, obs_seq)
def hmm_sample_numpy(params, seq_len, random_state=0): '\n Samples an observation of given length according to the defined\n hidden markov model and gives the sequence of the hidden states\n as well as the observation.\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n seq_len: array(seq_len)\n The length of the observation sequence\n\n random_state : int\n Seed value\n\n Returns\n -------\n * array(seq_len,)\n Hidden state sequence\n\n * array(seq_len,) :\n Observation sequence\n ' def sample_one_step_(hist, a, p): x_t = np.random.choice(a=a, p=p) return (np.append(hist, [x_t]), x_t) seed(random_state) (trans_mat, obs_mat, init_dist) = (params.trans_mat, params.obs_mat, params.init_dist) (n_states, n_obs) = obs_mat.shape state_seq = np.array([], dtype=int) obs_seq = np.array([], dtype=int) latent_states = np.arange(n_states) obs_states = np.arange(n_obs) (state_seq, zt) = sample_one_step_(state_seq, latent_states, init_dist) (obs_seq, xt) = sample_one_step_(obs_seq, obs_states, obs_mat[zt]) for _ in range(1, seq_len): (state_seq, zt) = sample_one_step_(state_seq, latent_states, trans_mat[zt]) (obs_seq, xt) = sample_one_step_(obs_seq, obs_states, obs_mat[zt]) return (state_seq, obs_seq)<|docstring|>Samples an observation of given length according to the defined hidden markov model and gives the sequence of the hidden states as well as the observation. Parameters ---------- params : HMMNumpy Hidden Markov Model seq_len: array(seq_len) The length of the observation sequence random_state : int Seed value Returns ------- * array(seq_len,) Hidden state sequence * array(seq_len,) : Observation sequence<|endoftext|>
e5f1964d4b087926a96151eb680ca75c62234afb726af2c8e2d84329d976cf6f
def hmm_forwards_numpy(params, obs_seq, length): '\n Calculates a belief state\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n obs_seq: array(seq_len)\n History of observable events\n\n Returns\n -------\n * float\n The loglikelihood giving log(p(x|model))\n\n * array(seq_len, n_hidden) :\n All alpha values found for each sample\n ' (trans_mat, obs_mat, init_dist) = (params.trans_mat, params.obs_mat, params.init_dist) (n_states, n_obs) = obs_mat.shape seq_len = len(obs_seq) alpha_hist = np.zeros((seq_len, n_states)) ll_hist = np.zeros(seq_len) alpha_n = (init_dist * obs_mat[(:, obs_seq[0])]) (alpha_n, cn) = normalize_numpy(alpha_n) alpha_hist[0] = alpha_n ll_hist[0] = np.log(cn) for t in range(1, length): alpha_n = (obs_mat[(:, obs_seq[t])] * (alpha_n[(:, None)] * trans_mat).sum(axis=0)) (alpha_n, cn) = normalize_numpy(alpha_n) alpha_hist[t] = alpha_n ll_hist[t] = (np.log(cn) + ll_hist[(t - 1)]) return (ll_hist[(length - 1)], alpha_hist)
Calculates a belief state Parameters ---------- params : HMMNumpy Hidden Markov Model obs_seq: array(seq_len) History of observable events Returns ------- * float The loglikelihood giving log(p(x|model)) * array(seq_len, n_hidden) : All alpha values found for each sample
jsl/hmm/hmm_numpy_lib.py
hmm_forwards_numpy
probml/JSL
23
python
def hmm_forwards_numpy(params, obs_seq, length): '\n Calculates a belief state\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n obs_seq: array(seq_len)\n History of observable events\n\n Returns\n -------\n * float\n The loglikelihood giving log(p(x|model))\n\n * array(seq_len, n_hidden) :\n All alpha values found for each sample\n ' (trans_mat, obs_mat, init_dist) = (params.trans_mat, params.obs_mat, params.init_dist) (n_states, n_obs) = obs_mat.shape seq_len = len(obs_seq) alpha_hist = np.zeros((seq_len, n_states)) ll_hist = np.zeros(seq_len) alpha_n = (init_dist * obs_mat[(:, obs_seq[0])]) (alpha_n, cn) = normalize_numpy(alpha_n) alpha_hist[0] = alpha_n ll_hist[0] = np.log(cn) for t in range(1, length): alpha_n = (obs_mat[(:, obs_seq[t])] * (alpha_n[(:, None)] * trans_mat).sum(axis=0)) (alpha_n, cn) = normalize_numpy(alpha_n) alpha_hist[t] = alpha_n ll_hist[t] = (np.log(cn) + ll_hist[(t - 1)]) return (ll_hist[(length - 1)], alpha_hist)
def hmm_forwards_numpy(params, obs_seq, length): '\n Calculates a belief state\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n obs_seq: array(seq_len)\n History of observable events\n\n Returns\n -------\n * float\n The loglikelihood giving log(p(x|model))\n\n * array(seq_len, n_hidden) :\n All alpha values found for each sample\n ' (trans_mat, obs_mat, init_dist) = (params.trans_mat, params.obs_mat, params.init_dist) (n_states, n_obs) = obs_mat.shape seq_len = len(obs_seq) alpha_hist = np.zeros((seq_len, n_states)) ll_hist = np.zeros(seq_len) alpha_n = (init_dist * obs_mat[(:, obs_seq[0])]) (alpha_n, cn) = normalize_numpy(alpha_n) alpha_hist[0] = alpha_n ll_hist[0] = np.log(cn) for t in range(1, length): alpha_n = (obs_mat[(:, obs_seq[t])] * (alpha_n[(:, None)] * trans_mat).sum(axis=0)) (alpha_n, cn) = normalize_numpy(alpha_n) alpha_hist[t] = alpha_n ll_hist[t] = (np.log(cn) + ll_hist[(t - 1)]) return (ll_hist[(length - 1)], alpha_hist)<|docstring|>Calculates a belief state Parameters ---------- params : HMMNumpy Hidden Markov Model obs_seq: array(seq_len) History of observable events Returns ------- * float The loglikelihood giving log(p(x|model)) * array(seq_len, n_hidden) : All alpha values found for each sample<|endoftext|>
1fab269f46ff4dc0859ec5e154c48f7b90f3872f44a650fcf586e3d51542470a
def hmm_loglikelihood_numpy(params, observations, lens): '\n Finds the loglikelihood of each observation sequence sequentially.\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n observations: array(N, seq_len)\n Batch of observation sequences\n\n lens : array(N, seq_len)\n Consists of the valid length of each observation sequence\n\n Returns\n -------\n * array(N, seq_len)\n Consists of the loglikelihood of each observation sequence\n ' return np.array([hmm_forwards_numpy(params, obs, length)[0] for (obs, length) in zip(observations, lens)])
Finds the loglikelihood of each observation sequence sequentially. Parameters ---------- params : HMMNumpy Hidden Markov Model observations: array(N, seq_len) Batch of observation sequences lens : array(N, seq_len) Consists of the valid length of each observation sequence Returns ------- * array(N, seq_len) Consists of the loglikelihood of each observation sequence
jsl/hmm/hmm_numpy_lib.py
hmm_loglikelihood_numpy
probml/JSL
23
python
def hmm_loglikelihood_numpy(params, observations, lens): '\n Finds the loglikelihood of each observation sequence sequentially.\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n observations: array(N, seq_len)\n Batch of observation sequences\n\n lens : array(N, seq_len)\n Consists of the valid length of each observation sequence\n\n Returns\n -------\n * array(N, seq_len)\n Consists of the loglikelihood of each observation sequence\n ' return np.array([hmm_forwards_numpy(params, obs, length)[0] for (obs, length) in zip(observations, lens)])
def hmm_loglikelihood_numpy(params, observations, lens): '\n Finds the loglikelihood of each observation sequence sequentially.\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n observations: array(N, seq_len)\n Batch of observation sequences\n\n lens : array(N, seq_len)\n Consists of the valid length of each observation sequence\n\n Returns\n -------\n * array(N, seq_len)\n Consists of the loglikelihood of each observation sequence\n ' return np.array([hmm_forwards_numpy(params, obs, length)[0] for (obs, length) in zip(observations, lens)])<|docstring|>Finds the loglikelihood of each observation sequence sequentially. Parameters ---------- params : HMMNumpy Hidden Markov Model observations: array(N, seq_len) Batch of observation sequences lens : array(N, seq_len) Consists of the valid length of each observation sequence Returns ------- * array(N, seq_len) Consists of the loglikelihood of each observation sequence<|endoftext|>
ad17d3597a50c344a54c2c07d58b398b31de8aa03681fc701406ce39dea623ae
def hmm_backwards_numpy(params, obs_seq, length=None): '\n Computes the backwards probabilities\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n obs_seq: array(seq_len,)\n History of observable events\n\n length : array(seq_len,)\n The valid length of the observation sequence\n\n Returns\n -------\n * array(seq_len, n_states)\n Beta values\n ' seq_len = len(obs_seq) if (length is None): length = seq_len (trans_mat, obs_mat, init_dist) = (params.trans_mat, params.obs_mat, params.init_dist) (n_states, n_obs) = obs_mat.shape beta_next = np.ones(n_states) beta_hist = np.zeros((seq_len, n_states)) beta_hist[(- 1)] = beta_next for t in range(2, (length + 1)): (beta_next, _) = normalize_numpy(((beta_next * obs_mat[(:, obs_seq[((- t) + 1)])]) * trans_mat).sum(axis=1)) beta_hist[(- t)] = beta_next return beta_hist
Computes the backwards probabilities Parameters ---------- params : HMMNumpy Hidden Markov Model obs_seq: array(seq_len,) History of observable events length : array(seq_len,) The valid length of the observation sequence Returns ------- * array(seq_len, n_states) Beta values
jsl/hmm/hmm_numpy_lib.py
hmm_backwards_numpy
probml/JSL
23
python
def hmm_backwards_numpy(params, obs_seq, length=None): '\n Computes the backwards probabilities\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n obs_seq: array(seq_len,)\n History of observable events\n\n length : array(seq_len,)\n The valid length of the observation sequence\n\n Returns\n -------\n * array(seq_len, n_states)\n Beta values\n ' seq_len = len(obs_seq) if (length is None): length = seq_len (trans_mat, obs_mat, init_dist) = (params.trans_mat, params.obs_mat, params.init_dist) (n_states, n_obs) = obs_mat.shape beta_next = np.ones(n_states) beta_hist = np.zeros((seq_len, n_states)) beta_hist[(- 1)] = beta_next for t in range(2, (length + 1)): (beta_next, _) = normalize_numpy(((beta_next * obs_mat[(:, obs_seq[((- t) + 1)])]) * trans_mat).sum(axis=1)) beta_hist[(- t)] = beta_next return beta_hist
def hmm_backwards_numpy(params, obs_seq, length=None): '\n Computes the backwards probabilities\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n obs_seq: array(seq_len,)\n History of observable events\n\n length : array(seq_len,)\n The valid length of the observation sequence\n\n Returns\n -------\n * array(seq_len, n_states)\n Beta values\n ' seq_len = len(obs_seq) if (length is None): length = seq_len (trans_mat, obs_mat, init_dist) = (params.trans_mat, params.obs_mat, params.init_dist) (n_states, n_obs) = obs_mat.shape beta_next = np.ones(n_states) beta_hist = np.zeros((seq_len, n_states)) beta_hist[(- 1)] = beta_next for t in range(2, (length + 1)): (beta_next, _) = normalize_numpy(((beta_next * obs_mat[(:, obs_seq[((- t) + 1)])]) * trans_mat).sum(axis=1)) beta_hist[(- t)] = beta_next return beta_hist<|docstring|>Computes the backwards probabilities Parameters ---------- params : HMMNumpy Hidden Markov Model obs_seq: array(seq_len,) History of observable events length : array(seq_len,) The valid length of the observation sequence Returns ------- * array(seq_len, n_states) Beta values<|endoftext|>
f9628bdaac0196cb224dd506171adc7f1c297365242ce3f63eaabd3435a18336
def hmm_forwards_backwards_numpy(params, obs_seq, length=None): '\n Computes, for each time step, the marginal conditional probability that the Hidden Markov Model was\n in each possible state given the observations that were made at each time step, i.e.\n P(z[i] | x[0], ..., x[num_steps - 1]) for all i from 0 to num_steps - 1\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n obs_seq: array(seq_len)\n History of observed states\n\n Returns\n -------\n * array(seq_len, n_states)\n Alpha values\n\n * array(seq_len, n_states)\n Beta values\n\n * array(seq_len, n_states)\n Marginal conditional probability\n\n * float\n The loglikelihood giving log(p(x|model))\n ' seq_len = len(obs_seq) if (length is None): length = seq_len (ll, alpha) = hmm_forwards_numpy(params, obs_seq, length) beta = hmm_backwards_numpy(params, obs_seq, length) gamma = (alpha * np.roll(beta, ((- seq_len) + length), axis=0)) normalizer = gamma.sum(axis=1, keepdims=True) gamma = (gamma / np.where((normalizer == 0), 1, normalizer)) return (alpha, beta, gamma, ll)
Computes, for each time step, the marginal conditional probability that the Hidden Markov Model was in each possible state given the observations that were made at each time step, i.e. P(z[i] | x[0], ..., x[num_steps - 1]) for all i from 0 to num_steps - 1 Parameters ---------- params : HMMNumpy Hidden Markov Model obs_seq: array(seq_len) History of observed states Returns ------- * array(seq_len, n_states) Alpha values * array(seq_len, n_states) Beta values * array(seq_len, n_states) Marginal conditional probability * float The loglikelihood giving log(p(x|model))
jsl/hmm/hmm_numpy_lib.py
hmm_forwards_backwards_numpy
probml/JSL
23
python
def hmm_forwards_backwards_numpy(params, obs_seq, length=None): '\n Computes, for each time step, the marginal conditional probability that the Hidden Markov Model was\n in each possible state given the observations that were made at each time step, i.e.\n P(z[i] | x[0], ..., x[num_steps - 1]) for all i from 0 to num_steps - 1\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n obs_seq: array(seq_len)\n History of observed states\n\n Returns\n -------\n * array(seq_len, n_states)\n Alpha values\n\n * array(seq_len, n_states)\n Beta values\n\n * array(seq_len, n_states)\n Marginal conditional probability\n\n * float\n The loglikelihood giving log(p(x|model))\n ' seq_len = len(obs_seq) if (length is None): length = seq_len (ll, alpha) = hmm_forwards_numpy(params, obs_seq, length) beta = hmm_backwards_numpy(params, obs_seq, length) gamma = (alpha * np.roll(beta, ((- seq_len) + length), axis=0)) normalizer = gamma.sum(axis=1, keepdims=True) gamma = (gamma / np.where((normalizer == 0), 1, normalizer)) return (alpha, beta, gamma, ll)
def hmm_forwards_backwards_numpy(params, obs_seq, length=None): '\n Computes, for each time step, the marginal conditional probability that the Hidden Markov Model was\n in each possible state given the observations that were made at each time step, i.e.\n P(z[i] | x[0], ..., x[num_steps - 1]) for all i from 0 to num_steps - 1\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n obs_seq: array(seq_len)\n History of observed states\n\n Returns\n -------\n * array(seq_len, n_states)\n Alpha values\n\n * array(seq_len, n_states)\n Beta values\n\n * array(seq_len, n_states)\n Marginal conditional probability\n\n * float\n The loglikelihood giving log(p(x|model))\n ' seq_len = len(obs_seq) if (length is None): length = seq_len (ll, alpha) = hmm_forwards_numpy(params, obs_seq, length) beta = hmm_backwards_numpy(params, obs_seq, length) gamma = (alpha * np.roll(beta, ((- seq_len) + length), axis=0)) normalizer = gamma.sum(axis=1, keepdims=True) gamma = (gamma / np.where((normalizer == 0), 1, normalizer)) return (alpha, beta, gamma, ll)<|docstring|>Computes, for each time step, the marginal conditional probability that the Hidden Markov Model was in each possible state given the observations that were made at each time step, i.e. P(z[i] | x[0], ..., x[num_steps - 1]) for all i from 0 to num_steps - 1 Parameters ---------- params : HMMNumpy Hidden Markov Model obs_seq: array(seq_len) History of observed states Returns ------- * array(seq_len, n_states) Alpha values * array(seq_len, n_states) Beta values * array(seq_len, n_states) Marginal conditional probability * float The loglikelihood giving log(p(x|model))<|endoftext|>
23ef5a38af3ffb7aeca5d7461a57a72c6a59a9f090c8fcf648aa0f786bc45da6
def hmm_viterbi_numpy(params, obs_seq): '\n Compute the most probable sequence of states\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n obs_seq: array(seq_len)\n History of observed states\n\n Returns\n -------\n * array(seq_len)\n Sequence of most MAP probable sequence of states\n ' seq_len = len(obs_seq) (trans_mat, obs_mat, init_dist) = (np.log(params.trans_mat), np.log(params.obs_mat), np.log(params.init_dist)) (n_states, _) = obs_mat.shape first_prob = (init_dist + obs_mat[(:, obs_seq[0])]) if (len(obs_seq) == 1): return np.expand_dims(np.argmax(first_prob), axis=0) prev_prob = first_prob most_likely_sources = [] for obs in obs_seq[1:]: obs_prob = obs_mat[(..., obs)] p = ((prev_prob[(..., None)] + trans_mat) + obs_prob[(..., None, :)]) max_p_given_successor = np.max(p, axis=(- 2)) most_likely_given_successor = np.argmax(p, axis=(- 2)) prev_prob = max_p_given_successor most_likely_sources.append(most_likely_given_successor) final_prob = prev_prob final_state = np.argmax(final_prob) most_likely_initial_given_successor = np.argmax((trans_mat + final_prob), axis=(- 2)) most_likely_sources = np.vstack([np.expand_dims(most_likely_initial_given_successor, axis=0), np.array(most_likely_sources)]) (most_likely_path, state) = ([], final_state) for most_likely_source in reversed(most_likely_sources[1:]): state = jax.nn.one_hot(state, n_states) most_likely = np.sum((most_likely_source * state)).astype(np.int64) state = most_likely most_likely_path.append(most_likely) return np.append(np.flip(most_likely_path), final_state)
Compute the most probable sequence of states Parameters ---------- params : HMMNumpy Hidden Markov Model obs_seq: array(seq_len) History of observed states Returns ------- * array(seq_len) Sequence of most MAP probable sequence of states
jsl/hmm/hmm_numpy_lib.py
hmm_viterbi_numpy
probml/JSL
23
python
def hmm_viterbi_numpy(params, obs_seq): '\n Compute the most probable sequence of states\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n obs_seq: array(seq_len)\n History of observed states\n\n Returns\n -------\n * array(seq_len)\n Sequence of most MAP probable sequence of states\n ' seq_len = len(obs_seq) (trans_mat, obs_mat, init_dist) = (np.log(params.trans_mat), np.log(params.obs_mat), np.log(params.init_dist)) (n_states, _) = obs_mat.shape first_prob = (init_dist + obs_mat[(:, obs_seq[0])]) if (len(obs_seq) == 1): return np.expand_dims(np.argmax(first_prob), axis=0) prev_prob = first_prob most_likely_sources = [] for obs in obs_seq[1:]: obs_prob = obs_mat[(..., obs)] p = ((prev_prob[(..., None)] + trans_mat) + obs_prob[(..., None, :)]) max_p_given_successor = np.max(p, axis=(- 2)) most_likely_given_successor = np.argmax(p, axis=(- 2)) prev_prob = max_p_given_successor most_likely_sources.append(most_likely_given_successor) final_prob = prev_prob final_state = np.argmax(final_prob) most_likely_initial_given_successor = np.argmax((trans_mat + final_prob), axis=(- 2)) most_likely_sources = np.vstack([np.expand_dims(most_likely_initial_given_successor, axis=0), np.array(most_likely_sources)]) (most_likely_path, state) = ([], final_state) for most_likely_source in reversed(most_likely_sources[1:]): state = jax.nn.one_hot(state, n_states) most_likely = np.sum((most_likely_source * state)).astype(np.int64) state = most_likely most_likely_path.append(most_likely) return np.append(np.flip(most_likely_path), final_state)
def hmm_viterbi_numpy(params, obs_seq): '\n Compute the most probable sequence of states\n\n Parameters\n ----------\n params : HMMNumpy\n Hidden Markov Model\n\n obs_seq: array(seq_len)\n History of observed states\n\n Returns\n -------\n * array(seq_len)\n Sequence of most MAP probable sequence of states\n ' seq_len = len(obs_seq) (trans_mat, obs_mat, init_dist) = (np.log(params.trans_mat), np.log(params.obs_mat), np.log(params.init_dist)) (n_states, _) = obs_mat.shape first_prob = (init_dist + obs_mat[(:, obs_seq[0])]) if (len(obs_seq) == 1): return np.expand_dims(np.argmax(first_prob), axis=0) prev_prob = first_prob most_likely_sources = [] for obs in obs_seq[1:]: obs_prob = obs_mat[(..., obs)] p = ((prev_prob[(..., None)] + trans_mat) + obs_prob[(..., None, :)]) max_p_given_successor = np.max(p, axis=(- 2)) most_likely_given_successor = np.argmax(p, axis=(- 2)) prev_prob = max_p_given_successor most_likely_sources.append(most_likely_given_successor) final_prob = prev_prob final_state = np.argmax(final_prob) most_likely_initial_given_successor = np.argmax((trans_mat + final_prob), axis=(- 2)) most_likely_sources = np.vstack([np.expand_dims(most_likely_initial_given_successor, axis=0), np.array(most_likely_sources)]) (most_likely_path, state) = ([], final_state) for most_likely_source in reversed(most_likely_sources[1:]): state = jax.nn.one_hot(state, n_states) most_likely = np.sum((most_likely_source * state)).astype(np.int64) state = most_likely most_likely_path.append(most_likely) return np.append(np.flip(most_likely_path), final_state)<|docstring|>Compute the most probable sequence of states Parameters ---------- params : HMMNumpy Hidden Markov Model obs_seq: array(seq_len) History of observed states Returns ------- * array(seq_len) Sequence of most MAP probable sequence of states<|endoftext|>
524411905aa041167fde4903b8c41aba9e3c34e8b89183741525ab779fc0f9ae
def init_random_params_numpy(sizes, random_state): '\n Initializes the components of HMM from normal distibution\n\n Parameters\n ----------\n sizes: List\n Consists of the number of hidden states and observable events, respectively\n\n random_state : int\n Seed value\n\n Returns\n -------\n * HMMNumpy\n Hidden Markov Model\n ' (num_hidden, num_obs) = sizes np.random.seed(random_state) return HMMNumpy(softmax(np.random.randn(num_hidden, num_hidden), axis=1), softmax(np.random.randn(num_hidden, num_obs), axis=1), softmax(np.random.randn(num_hidden)))
Initializes the components of HMM from normal distibution Parameters ---------- sizes: List Consists of the number of hidden states and observable events, respectively random_state : int Seed value Returns ------- * HMMNumpy Hidden Markov Model
jsl/hmm/hmm_numpy_lib.py
init_random_params_numpy
probml/JSL
23
python
def init_random_params_numpy(sizes, random_state): '\n Initializes the components of HMM from normal distibution\n\n Parameters\n ----------\n sizes: List\n Consists of the number of hidden states and observable events, respectively\n\n random_state : int\n Seed value\n\n Returns\n -------\n * HMMNumpy\n Hidden Markov Model\n ' (num_hidden, num_obs) = sizes np.random.seed(random_state) return HMMNumpy(softmax(np.random.randn(num_hidden, num_hidden), axis=1), softmax(np.random.randn(num_hidden, num_obs), axis=1), softmax(np.random.randn(num_hidden)))
def init_random_params_numpy(sizes, random_state): '\n Initializes the components of HMM from normal distibution\n\n Parameters\n ----------\n sizes: List\n Consists of the number of hidden states and observable events, respectively\n\n random_state : int\n Seed value\n\n Returns\n -------\n * HMMNumpy\n Hidden Markov Model\n ' (num_hidden, num_obs) = sizes np.random.seed(random_state) return HMMNumpy(softmax(np.random.randn(num_hidden, num_hidden), axis=1), softmax(np.random.randn(num_hidden, num_obs), axis=1), softmax(np.random.randn(num_hidden)))<|docstring|>Initializes the components of HMM from normal distibution Parameters ---------- sizes: List Consists of the number of hidden states and observable events, respectively random_state : int Seed value Returns ------- * HMMNumpy Hidden Markov Model<|endoftext|>
b20d62985c9edc6ae22db0e10d801b8a83ca23f1842798f004e189be7bdbddc5
def compute_expected_trans_counts_numpy(params, alpha, beta, obs, T): '\n Computes the expected transition counts by summing ksi_{jk} for the observation given for all states j and k.\n ksi_{jk} for any time t in [0, T-1] can be calculated as the multiplication of the probability of ending\n in state j at t, the probability of starting in state k at t+1, the transition probability a_{jk} and b_{k obs[t+1]}.\n Note that ksi[t] is normalized so that the probabilities sums up to 1 for each time t in [0, T-1].\n\n Parameters\n ----------\n params: HMMNumpy\n Hidden Markov Model\n\n alpha : array\n A matrix of shape (seq_len, n_states)\n\n beta : array\n A matrix of shape (seq_len, n_states)\n\n obs : array\n One observation sequence\n\n T : int\n The valid length of observation sequence\n\n Returns\n ----------\n\n * array\n The matrix of shape (n_states, n_states) representing expected transition counts given obs o.\n ' (trans_mat, obs_mat, init_dist) = (params.trans_mat, params.obs_mat, params.init_dist) (n_states, n_obs) = obs_mat.shape AA = np.zeros((n_states, n_states)) for t in range((T - 1)): ksi = (((alpha[t] * trans_mat.T) * beta[(t + 1)]) * obs_mat[(:, obs[(t + 1)])]) normalizer = ksi.sum() ksi /= (1 if (normalizer == 0) else ksi.sum()) AA += ksi.T return AA
Computes the expected transition counts by summing ksi_{jk} for the observation given for all states j and k. ksi_{jk} for any time t in [0, T-1] can be calculated as the multiplication of the probability of ending in state j at t, the probability of starting in state k at t+1, the transition probability a_{jk} and b_{k obs[t+1]}. Note that ksi[t] is normalized so that the probabilities sums up to 1 for each time t in [0, T-1]. Parameters ---------- params: HMMNumpy Hidden Markov Model alpha : array A matrix of shape (seq_len, n_states) beta : array A matrix of shape (seq_len, n_states) obs : array One observation sequence T : int The valid length of observation sequence Returns ---------- * array The matrix of shape (n_states, n_states) representing expected transition counts given obs o.
jsl/hmm/hmm_numpy_lib.py
compute_expected_trans_counts_numpy
probml/JSL
23
python
def compute_expected_trans_counts_numpy(params, alpha, beta, obs, T): '\n Computes the expected transition counts by summing ksi_{jk} for the observation given for all states j and k.\n ksi_{jk} for any time t in [0, T-1] can be calculated as the multiplication of the probability of ending\n in state j at t, the probability of starting in state k at t+1, the transition probability a_{jk} and b_{k obs[t+1]}.\n Note that ksi[t] is normalized so that the probabilities sums up to 1 for each time t in [0, T-1].\n\n Parameters\n ----------\n params: HMMNumpy\n Hidden Markov Model\n\n alpha : array\n A matrix of shape (seq_len, n_states)\n\n beta : array\n A matrix of shape (seq_len, n_states)\n\n obs : array\n One observation sequence\n\n T : int\n The valid length of observation sequence\n\n Returns\n ----------\n\n * array\n The matrix of shape (n_states, n_states) representing expected transition counts given obs o.\n ' (trans_mat, obs_mat, init_dist) = (params.trans_mat, params.obs_mat, params.init_dist) (n_states, n_obs) = obs_mat.shape AA = np.zeros((n_states, n_states)) for t in range((T - 1)): ksi = (((alpha[t] * trans_mat.T) * beta[(t + 1)]) * obs_mat[(:, obs[(t + 1)])]) normalizer = ksi.sum() ksi /= (1 if (normalizer == 0) else ksi.sum()) AA += ksi.T return AA
def compute_expected_trans_counts_numpy(params, alpha, beta, obs, T): '\n Computes the expected transition counts by summing ksi_{jk} for the observation given for all states j and k.\n ksi_{jk} for any time t in [0, T-1] can be calculated as the multiplication of the probability of ending\n in state j at t, the probability of starting in state k at t+1, the transition probability a_{jk} and b_{k obs[t+1]}.\n Note that ksi[t] is normalized so that the probabilities sums up to 1 for each time t in [0, T-1].\n\n Parameters\n ----------\n params: HMMNumpy\n Hidden Markov Model\n\n alpha : array\n A matrix of shape (seq_len, n_states)\n\n beta : array\n A matrix of shape (seq_len, n_states)\n\n obs : array\n One observation sequence\n\n T : int\n The valid length of observation sequence\n\n Returns\n ----------\n\n * array\n The matrix of shape (n_states, n_states) representing expected transition counts given obs o.\n ' (trans_mat, obs_mat, init_dist) = (params.trans_mat, params.obs_mat, params.init_dist) (n_states, n_obs) = obs_mat.shape AA = np.zeros((n_states, n_states)) for t in range((T - 1)): ksi = (((alpha[t] * trans_mat.T) * beta[(t + 1)]) * obs_mat[(:, obs[(t + 1)])]) normalizer = ksi.sum() ksi /= (1 if (normalizer == 0) else ksi.sum()) AA += ksi.T return AA<|docstring|>Computes the expected transition counts by summing ksi_{jk} for the observation given for all states j and k. ksi_{jk} for any time t in [0, T-1] can be calculated as the multiplication of the probability of ending in state j at t, the probability of starting in state k at t+1, the transition probability a_{jk} and b_{k obs[t+1]}. Note that ksi[t] is normalized so that the probabilities sums up to 1 for each time t in [0, T-1]. Parameters ---------- params: HMMNumpy Hidden Markov Model alpha : array A matrix of shape (seq_len, n_states) beta : array A matrix of shape (seq_len, n_states) obs : array One observation sequence T : int The valid length of observation sequence Returns ---------- * array The matrix of shape (n_states, n_states) representing expected transition counts given obs o.<|endoftext|>
d3f7901ccfa7b7d8e16774ba6060b6aa925b6a594995e95553b44483de35e3e4
def compute_expected_obs_counts_numpy(gamma, obs, T, n_states, n_obs): '\n Computes the expected observation count for each observation o by summing the probability of being at any of the\n states for each time t.\n Parameters\n ----------\n gamma : array\n A matrix of shape (seq_len, n_states)\n\n obs : array\n An array of shape (seq_len,)\n\n T : int\n The valid length of observation sequence\n\n n_states : int\n The number of hidden states\n\n n_obs : int\n The number of observable events\n\n Returns\n ----------\n * array\n A matrix of shape (n_states, n_obs) representing expected observation counts given observation sequence.\n ' BB = np.zeros((n_states, n_obs)) for t in range(T): o = obs[t] BB[(:, o)] += gamma[t] return BB
Computes the expected observation count for each observation o by summing the probability of being at any of the states for each time t. Parameters ---------- gamma : array A matrix of shape (seq_len, n_states) obs : array An array of shape (seq_len,) T : int The valid length of observation sequence n_states : int The number of hidden states n_obs : int The number of observable events Returns ---------- * array A matrix of shape (n_states, n_obs) representing expected observation counts given observation sequence.
jsl/hmm/hmm_numpy_lib.py
compute_expected_obs_counts_numpy
probml/JSL
23
python
def compute_expected_obs_counts_numpy(gamma, obs, T, n_states, n_obs): '\n Computes the expected observation count for each observation o by summing the probability of being at any of the\n states for each time t.\n Parameters\n ----------\n gamma : array\n A matrix of shape (seq_len, n_states)\n\n obs : array\n An array of shape (seq_len,)\n\n T : int\n The valid length of observation sequence\n\n n_states : int\n The number of hidden states\n\n n_obs : int\n The number of observable events\n\n Returns\n ----------\n * array\n A matrix of shape (n_states, n_obs) representing expected observation counts given observation sequence.\n ' BB = np.zeros((n_states, n_obs)) for t in range(T): o = obs[t] BB[(:, o)] += gamma[t] return BB
def compute_expected_obs_counts_numpy(gamma, obs, T, n_states, n_obs): '\n Computes the expected observation count for each observation o by summing the probability of being at any of the\n states for each time t.\n Parameters\n ----------\n gamma : array\n A matrix of shape (seq_len, n_states)\n\n obs : array\n An array of shape (seq_len,)\n\n T : int\n The valid length of observation sequence\n\n n_states : int\n The number of hidden states\n\n n_obs : int\n The number of observable events\n\n Returns\n ----------\n * array\n A matrix of shape (n_states, n_obs) representing expected observation counts given observation sequence.\n ' BB = np.zeros((n_states, n_obs)) for t in range(T): o = obs[t] BB[(:, o)] += gamma[t] return BB<|docstring|>Computes the expected observation count for each observation o by summing the probability of being at any of the states for each time t. Parameters ---------- gamma : array A matrix of shape (seq_len, n_states) obs : array An array of shape (seq_len,) T : int The valid length of observation sequence n_states : int The number of hidden states n_obs : int The number of observable events Returns ---------- * array A matrix of shape (n_states, n_obs) representing expected observation counts given observation sequence.<|endoftext|>
6051e625d9fd9808a6f13d1b81d6c97ec4be721d55ea150ec168a1c1c9241c7c
def hmm_e_step_numpy(params, observations, valid_lengths): '\n\n Calculates the the expectation of the complete loglikelihood over the distribution of\n observations given the current parameters\n\n Parameters\n ----------\n params: HMMNumpy\n Hidden Markov Model\n\n observations : array\n All observation sequences\n\n valid_lengths : array\n Valid lengths of each observation sequence\n\n Returns\n ----------\n * array\n A matrix of shape (n_states, n_states) representing expected transition counts\n\n * array\n A matrix of shape (n_states, n_obs) representing expected observation counts\n\n * array\n An array of shape (n_states,) representing expected initial counts calculated from summing gamma[0] of each\n observation sequence\n\n * float\n The sum of the likelihood, p(o | lambda) where lambda stands for (trans_mat, obs_mat, init_dist) triple, for\n each observation sequence o.\n ' (N, _) = observations.shape (trans_mat, obs_mat, init_dist) = (params.trans_mat, params.obs_mat, params.init_dist) (n_states, n_obs) = obs_mat.shape trans_counts = np.zeros((n_states, n_states)) obs_counts = np.zeros((n_states, n_obs)) init_counts = np.zeros(n_states) loglikelihood = 0 for (obs, valid_len) in zip(observations, valid_lengths): (alpha, beta, gamma, ll) = hmm_forwards_backwards_numpy(params, obs, valid_len) trans_counts = (trans_counts + compute_expected_trans_counts_numpy(params, alpha, beta, obs, valid_len)) obs_counts = (obs_counts + compute_expected_obs_counts_numpy(gamma, obs, valid_len, n_states, n_obs)) init_counts = (init_counts + gamma[0]) loglikelihood += ll return (trans_counts, obs_counts, init_counts, loglikelihood)
Calculates the the expectation of the complete loglikelihood over the distribution of observations given the current parameters Parameters ---------- params: HMMNumpy Hidden Markov Model observations : array All observation sequences valid_lengths : array Valid lengths of each observation sequence Returns ---------- * array A matrix of shape (n_states, n_states) representing expected transition counts * array A matrix of shape (n_states, n_obs) representing expected observation counts * array An array of shape (n_states,) representing expected initial counts calculated from summing gamma[0] of each observation sequence * float The sum of the likelihood, p(o | lambda) where lambda stands for (trans_mat, obs_mat, init_dist) triple, for each observation sequence o.
jsl/hmm/hmm_numpy_lib.py
hmm_e_step_numpy
probml/JSL
23
python
def hmm_e_step_numpy(params, observations, valid_lengths): '\n\n Calculates the the expectation of the complete loglikelihood over the distribution of\n observations given the current parameters\n\n Parameters\n ----------\n params: HMMNumpy\n Hidden Markov Model\n\n observations : array\n All observation sequences\n\n valid_lengths : array\n Valid lengths of each observation sequence\n\n Returns\n ----------\n * array\n A matrix of shape (n_states, n_states) representing expected transition counts\n\n * array\n A matrix of shape (n_states, n_obs) representing expected observation counts\n\n * array\n An array of shape (n_states,) representing expected initial counts calculated from summing gamma[0] of each\n observation sequence\n\n * float\n The sum of the likelihood, p(o | lambda) where lambda stands for (trans_mat, obs_mat, init_dist) triple, for\n each observation sequence o.\n ' (N, _) = observations.shape (trans_mat, obs_mat, init_dist) = (params.trans_mat, params.obs_mat, params.init_dist) (n_states, n_obs) = obs_mat.shape trans_counts = np.zeros((n_states, n_states)) obs_counts = np.zeros((n_states, n_obs)) init_counts = np.zeros(n_states) loglikelihood = 0 for (obs, valid_len) in zip(observations, valid_lengths): (alpha, beta, gamma, ll) = hmm_forwards_backwards_numpy(params, obs, valid_len) trans_counts = (trans_counts + compute_expected_trans_counts_numpy(params, alpha, beta, obs, valid_len)) obs_counts = (obs_counts + compute_expected_obs_counts_numpy(gamma, obs, valid_len, n_states, n_obs)) init_counts = (init_counts + gamma[0]) loglikelihood += ll return (trans_counts, obs_counts, init_counts, loglikelihood)
def hmm_e_step_numpy(params, observations, valid_lengths): '\n\n Calculates the the expectation of the complete loglikelihood over the distribution of\n observations given the current parameters\n\n Parameters\n ----------\n params: HMMNumpy\n Hidden Markov Model\n\n observations : array\n All observation sequences\n\n valid_lengths : array\n Valid lengths of each observation sequence\n\n Returns\n ----------\n * array\n A matrix of shape (n_states, n_states) representing expected transition counts\n\n * array\n A matrix of shape (n_states, n_obs) representing expected observation counts\n\n * array\n An array of shape (n_states,) representing expected initial counts calculated from summing gamma[0] of each\n observation sequence\n\n * float\n The sum of the likelihood, p(o | lambda) where lambda stands for (trans_mat, obs_mat, init_dist) triple, for\n each observation sequence o.\n ' (N, _) = observations.shape (trans_mat, obs_mat, init_dist) = (params.trans_mat, params.obs_mat, params.init_dist) (n_states, n_obs) = obs_mat.shape trans_counts = np.zeros((n_states, n_states)) obs_counts = np.zeros((n_states, n_obs)) init_counts = np.zeros(n_states) loglikelihood = 0 for (obs, valid_len) in zip(observations, valid_lengths): (alpha, beta, gamma, ll) = hmm_forwards_backwards_numpy(params, obs, valid_len) trans_counts = (trans_counts + compute_expected_trans_counts_numpy(params, alpha, beta, obs, valid_len)) obs_counts = (obs_counts + compute_expected_obs_counts_numpy(gamma, obs, valid_len, n_states, n_obs)) init_counts = (init_counts + gamma[0]) loglikelihood += ll return (trans_counts, obs_counts, init_counts, loglikelihood)<|docstring|>Calculates the the expectation of the complete loglikelihood over the distribution of observations given the current parameters Parameters ---------- params: HMMNumpy Hidden Markov Model observations : array All observation sequences valid_lengths : array Valid lengths of each observation sequence Returns ---------- * array A matrix of shape (n_states, n_states) representing expected transition counts * array A matrix of shape (n_states, n_obs) representing expected observation counts * array An array of shape (n_states,) representing expected initial counts calculated from summing gamma[0] of each observation sequence * float The sum of the likelihood, p(o | lambda) where lambda stands for (trans_mat, obs_mat, init_dist) triple, for each observation sequence o.<|endoftext|>
7381a6dd6b9b2638c0c6fbbb1a009de5fe2a0bb2fc886de2f0abf373ccdeebb1
def hmm_m_step_numpy(counts, priors=None): '\n\n Recomputes new parameters from A, B and pi using max likelihood.\n\n Parameters\n ----------\n counts: tuple\n Consists of expected transition counts, expected observation counts, and expected initial state counts,\n respectively.\n\n priors : PriorsNumpy\n\n Returns\n ----------\n * HMMNumpy\n Hidden Markov Model\n\n ' (trans_counts, obs_counts, init_counts) = counts if (priors is not None): trans_counts = (trans_counts + priors.trans_pseudo_counts) obs_counts = (obs_counts + priors.obs_pseudo_count) init_counts = (init_counts + priors.init_pseudo_counts) A = (trans_counts / trans_counts.sum(axis=1, keepdims=True)) B = (obs_counts / obs_counts.sum(axis=1, keepdims=True)) pi = (init_counts / init_counts.sum()) return HMMNumpy(A, B, pi)
Recomputes new parameters from A, B and pi using max likelihood. Parameters ---------- counts: tuple Consists of expected transition counts, expected observation counts, and expected initial state counts, respectively. priors : PriorsNumpy Returns ---------- * HMMNumpy Hidden Markov Model
jsl/hmm/hmm_numpy_lib.py
hmm_m_step_numpy
probml/JSL
23
python
def hmm_m_step_numpy(counts, priors=None): '\n\n Recomputes new parameters from A, B and pi using max likelihood.\n\n Parameters\n ----------\n counts: tuple\n Consists of expected transition counts, expected observation counts, and expected initial state counts,\n respectively.\n\n priors : PriorsNumpy\n\n Returns\n ----------\n * HMMNumpy\n Hidden Markov Model\n\n ' (trans_counts, obs_counts, init_counts) = counts if (priors is not None): trans_counts = (trans_counts + priors.trans_pseudo_counts) obs_counts = (obs_counts + priors.obs_pseudo_count) init_counts = (init_counts + priors.init_pseudo_counts) A = (trans_counts / trans_counts.sum(axis=1, keepdims=True)) B = (obs_counts / obs_counts.sum(axis=1, keepdims=True)) pi = (init_counts / init_counts.sum()) return HMMNumpy(A, B, pi)
def hmm_m_step_numpy(counts, priors=None): '\n\n Recomputes new parameters from A, B and pi using max likelihood.\n\n Parameters\n ----------\n counts: tuple\n Consists of expected transition counts, expected observation counts, and expected initial state counts,\n respectively.\n\n priors : PriorsNumpy\n\n Returns\n ----------\n * HMMNumpy\n Hidden Markov Model\n\n ' (trans_counts, obs_counts, init_counts) = counts if (priors is not None): trans_counts = (trans_counts + priors.trans_pseudo_counts) obs_counts = (obs_counts + priors.obs_pseudo_count) init_counts = (init_counts + priors.init_pseudo_counts) A = (trans_counts / trans_counts.sum(axis=1, keepdims=True)) B = (obs_counts / obs_counts.sum(axis=1, keepdims=True)) pi = (init_counts / init_counts.sum()) return HMMNumpy(A, B, pi)<|docstring|>Recomputes new parameters from A, B and pi using max likelihood. Parameters ---------- counts: tuple Consists of expected transition counts, expected observation counts, and expected initial state counts, respectively. priors : PriorsNumpy Returns ---------- * HMMNumpy Hidden Markov Model<|endoftext|>
d42cb8fb1271be0f42ca842886071cfaae5fec68cdbd7c7eea9aee95fd09bf8d
def hmm_em_numpy(observations, valid_lengths, n_hidden=None, n_obs=None, init_params=None, priors=None, num_epochs=1, random_state=None): '\n Implements Baum–Welch algorithm which is used for finding its components, A, B and pi.\n\n Parameters\n ----------\n observations: array\n All observation sequences\n\n valid_lengths : array\n Valid lengths of each observation sequence\n\n n_hidden : int\n The number of hidden states\n\n n_obs : int\n The number of observable events\n\n init_params : HMMNumpy\n Initial Hidden Markov Model\n\n priors : PriorsNumpy\n Priors for the components of Hidden Markov Model\n\n num_epochs : int\n Number of times model will be trained\n\n random_state: int\n Seed value\n\n Returns\n ----------\n * HMMNumpy\n Trained Hidden Markov Model\n\n * array\n Negative loglikelihoods each of which can be interpreted as the loss value at the current iteration.\n ' if (random_state is None): random_state = 0 if (init_params is None): try: init_params = init_random_params_numpy([n_hidden, n_obs], random_state) except: raise ValueError('n_hidden and n_obs should be specified when init_params was not given.') neg_loglikelihoods = [] params = init_params for _ in range(num_epochs): (trans_counts, obs_counts, init_counts, ll) = hmm_e_step_numpy(params, observations, valid_lengths) neg_loglikelihoods.append((- ll)) params = hmm_m_step_numpy([trans_counts, obs_counts, init_counts], priors) return (params, neg_loglikelihoods)
Implements Baum–Welch algorithm which is used for finding its components, A, B and pi. Parameters ---------- observations: array All observation sequences valid_lengths : array Valid lengths of each observation sequence n_hidden : int The number of hidden states n_obs : int The number of observable events init_params : HMMNumpy Initial Hidden Markov Model priors : PriorsNumpy Priors for the components of Hidden Markov Model num_epochs : int Number of times model will be trained random_state: int Seed value Returns ---------- * HMMNumpy Trained Hidden Markov Model * array Negative loglikelihoods each of which can be interpreted as the loss value at the current iteration.
jsl/hmm/hmm_numpy_lib.py
hmm_em_numpy
probml/JSL
23
python
def hmm_em_numpy(observations, valid_lengths, n_hidden=None, n_obs=None, init_params=None, priors=None, num_epochs=1, random_state=None): '\n Implements Baum–Welch algorithm which is used for finding its components, A, B and pi.\n\n Parameters\n ----------\n observations: array\n All observation sequences\n\n valid_lengths : array\n Valid lengths of each observation sequence\n\n n_hidden : int\n The number of hidden states\n\n n_obs : int\n The number of observable events\n\n init_params : HMMNumpy\n Initial Hidden Markov Model\n\n priors : PriorsNumpy\n Priors for the components of Hidden Markov Model\n\n num_epochs : int\n Number of times model will be trained\n\n random_state: int\n Seed value\n\n Returns\n ----------\n * HMMNumpy\n Trained Hidden Markov Model\n\n * array\n Negative loglikelihoods each of which can be interpreted as the loss value at the current iteration.\n ' if (random_state is None): random_state = 0 if (init_params is None): try: init_params = init_random_params_numpy([n_hidden, n_obs], random_state) except: raise ValueError('n_hidden and n_obs should be specified when init_params was not given.') neg_loglikelihoods = [] params = init_params for _ in range(num_epochs): (trans_counts, obs_counts, init_counts, ll) = hmm_e_step_numpy(params, observations, valid_lengths) neg_loglikelihoods.append((- ll)) params = hmm_m_step_numpy([trans_counts, obs_counts, init_counts], priors) return (params, neg_loglikelihoods)
def hmm_em_numpy(observations, valid_lengths, n_hidden=None, n_obs=None, init_params=None, priors=None, num_epochs=1, random_state=None): '\n Implements Baum–Welch algorithm which is used for finding its components, A, B and pi.\n\n Parameters\n ----------\n observations: array\n All observation sequences\n\n valid_lengths : array\n Valid lengths of each observation sequence\n\n n_hidden : int\n The number of hidden states\n\n n_obs : int\n The number of observable events\n\n init_params : HMMNumpy\n Initial Hidden Markov Model\n\n priors : PriorsNumpy\n Priors for the components of Hidden Markov Model\n\n num_epochs : int\n Number of times model will be trained\n\n random_state: int\n Seed value\n\n Returns\n ----------\n * HMMNumpy\n Trained Hidden Markov Model\n\n * array\n Negative loglikelihoods each of which can be interpreted as the loss value at the current iteration.\n ' if (random_state is None): random_state = 0 if (init_params is None): try: init_params = init_random_params_numpy([n_hidden, n_obs], random_state) except: raise ValueError('n_hidden and n_obs should be specified when init_params was not given.') neg_loglikelihoods = [] params = init_params for _ in range(num_epochs): (trans_counts, obs_counts, init_counts, ll) = hmm_e_step_numpy(params, observations, valid_lengths) neg_loglikelihoods.append((- ll)) params = hmm_m_step_numpy([trans_counts, obs_counts, init_counts], priors) return (params, neg_loglikelihoods)<|docstring|>Implements Baum–Welch algorithm which is used for finding its components, A, B and pi. Parameters ---------- observations: array All observation sequences valid_lengths : array Valid lengths of each observation sequence n_hidden : int The number of hidden states n_obs : int The number of observable events init_params : HMMNumpy Initial Hidden Markov Model priors : PriorsNumpy Priors for the components of Hidden Markov Model num_epochs : int Number of times model will be trained random_state: int Seed value Returns ---------- * HMMNumpy Trained Hidden Markov Model * array Negative loglikelihoods each of which can be interpreted as the loss value at the current iteration.<|endoftext|>
fe34fa27350f5a970c62755764141b420b0913151ab1891945898a7b680ea0ea
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]=None, failover_group_name: Optional[pulumi.Input[str]]=None, location_name: Optional[pulumi.Input[str]]=None, managed_instance_pairs: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ManagedInstancePairInfoArgs']]]]]=None, partner_regions: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['PartnerRegionInfoArgs']]]]]=None, read_only_endpoint: Optional[pulumi.Input[pulumi.InputType['InstanceFailoverGroupReadOnlyEndpointArgs']]]=None, read_write_endpoint: Optional[pulumi.Input[pulumi.InputType['InstanceFailoverGroupReadWriteEndpointArgs']]]=None, resource_group_name: Optional[pulumi.Input[str]]=None, __props__=None, __name__=None, __opts__=None): "\n An instance failover group.\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] failover_group_name: The name of the failover group.\n :param pulumi.Input[str] location_name: The name of the region where the resource is located.\n :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ManagedInstancePairInfoArgs']]]] managed_instance_pairs: List of managed instance pairs in the failover group.\n :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['PartnerRegionInfoArgs']]]] partner_regions: Partner region information for the failover group.\n :param pulumi.Input[pulumi.InputType['InstanceFailoverGroupReadOnlyEndpointArgs']] read_only_endpoint: Read-only endpoint of the failover group instance.\n :param pulumi.Input[pulumi.InputType['InstanceFailoverGroupReadWriteEndpointArgs']] read_write_endpoint: Read-write endpoint of the failover group instance.\n :param pulumi.Input[str] resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.\n " if (__name__ is not None): warnings.warn('explicit use of __name__ is deprecated', DeprecationWarning) resource_name = __name__ if (__opts__ is not None): warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if (opts is None): opts = pulumi.ResourceOptions() if (not isinstance(opts, pulumi.ResourceOptions)): raise TypeError('Expected resource options to be a ResourceOptions instance') if (opts.version is None): opts.version = _utilities.get_version() if (opts.id is None): if (__props__ is not None): raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['failover_group_name'] = failover_group_name if ((location_name is None) and (not opts.urn)): raise TypeError("Missing required property 'location_name'") __props__['location_name'] = location_name if ((managed_instance_pairs is None) and (not opts.urn)): raise TypeError("Missing required property 'managed_instance_pairs'") __props__['managed_instance_pairs'] = managed_instance_pairs if ((partner_regions is None) and (not opts.urn)): raise TypeError("Missing required property 'partner_regions'") __props__['partner_regions'] = partner_regions __props__['read_only_endpoint'] = read_only_endpoint if ((read_write_endpoint is None) and (not opts.urn)): raise TypeError("Missing required property 'read_write_endpoint'") __props__['read_write_endpoint'] = read_write_endpoint if ((resource_group_name is None) and (not opts.urn)): raise TypeError("Missing required property 'resource_group_name'") __props__['resource_group_name'] = resource_group_name __props__['name'] = None __props__['replication_role'] = None __props__['replication_state'] = None __props__['type'] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_='azure-nextgen:sql:InstanceFailoverGroup'), pulumi.Alias(type_='azure-nextgen:sql/v20200202preview:InstanceFailoverGroup'), pulumi.Alias(type_='azure-nextgen:sql/v20200801preview:InstanceFailoverGroup')]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(InstanceFailoverGroup, __self__).__init__('azure-nextgen:sql/v20171001preview:InstanceFailoverGroup', resource_name, __props__, opts)
An instance failover group. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] failover_group_name: The name of the failover group. :param pulumi.Input[str] location_name: The name of the region where the resource is located. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ManagedInstancePairInfoArgs']]]] managed_instance_pairs: List of managed instance pairs in the failover group. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['PartnerRegionInfoArgs']]]] partner_regions: Partner region information for the failover group. :param pulumi.Input[pulumi.InputType['InstanceFailoverGroupReadOnlyEndpointArgs']] read_only_endpoint: Read-only endpoint of the failover group instance. :param pulumi.Input[pulumi.InputType['InstanceFailoverGroupReadWriteEndpointArgs']] read_write_endpoint: Read-write endpoint of the failover group instance. :param pulumi.Input[str] resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
sdk/python/pulumi_azure_nextgen/sql/v20171001preview/instance_failover_group.py
__init__
pulumi/pulumi-azure-nextgen
31
python
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]=None, failover_group_name: Optional[pulumi.Input[str]]=None, location_name: Optional[pulumi.Input[str]]=None, managed_instance_pairs: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ManagedInstancePairInfoArgs']]]]]=None, partner_regions: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['PartnerRegionInfoArgs']]]]]=None, read_only_endpoint: Optional[pulumi.Input[pulumi.InputType['InstanceFailoverGroupReadOnlyEndpointArgs']]]=None, read_write_endpoint: Optional[pulumi.Input[pulumi.InputType['InstanceFailoverGroupReadWriteEndpointArgs']]]=None, resource_group_name: Optional[pulumi.Input[str]]=None, __props__=None, __name__=None, __opts__=None): "\n An instance failover group.\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] failover_group_name: The name of the failover group.\n :param pulumi.Input[str] location_name: The name of the region where the resource is located.\n :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ManagedInstancePairInfoArgs']]]] managed_instance_pairs: List of managed instance pairs in the failover group.\n :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['PartnerRegionInfoArgs']]]] partner_regions: Partner region information for the failover group.\n :param pulumi.Input[pulumi.InputType['InstanceFailoverGroupReadOnlyEndpointArgs']] read_only_endpoint: Read-only endpoint of the failover group instance.\n :param pulumi.Input[pulumi.InputType['InstanceFailoverGroupReadWriteEndpointArgs']] read_write_endpoint: Read-write endpoint of the failover group instance.\n :param pulumi.Input[str] resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.\n " if (__name__ is not None): warnings.warn('explicit use of __name__ is deprecated', DeprecationWarning) resource_name = __name__ if (__opts__ is not None): warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if (opts is None): opts = pulumi.ResourceOptions() if (not isinstance(opts, pulumi.ResourceOptions)): raise TypeError('Expected resource options to be a ResourceOptions instance') if (opts.version is None): opts.version = _utilities.get_version() if (opts.id is None): if (__props__ is not None): raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['failover_group_name'] = failover_group_name if ((location_name is None) and (not opts.urn)): raise TypeError("Missing required property 'location_name'") __props__['location_name'] = location_name if ((managed_instance_pairs is None) and (not opts.urn)): raise TypeError("Missing required property 'managed_instance_pairs'") __props__['managed_instance_pairs'] = managed_instance_pairs if ((partner_regions is None) and (not opts.urn)): raise TypeError("Missing required property 'partner_regions'") __props__['partner_regions'] = partner_regions __props__['read_only_endpoint'] = read_only_endpoint if ((read_write_endpoint is None) and (not opts.urn)): raise TypeError("Missing required property 'read_write_endpoint'") __props__['read_write_endpoint'] = read_write_endpoint if ((resource_group_name is None) and (not opts.urn)): raise TypeError("Missing required property 'resource_group_name'") __props__['resource_group_name'] = resource_group_name __props__['name'] = None __props__['replication_role'] = None __props__['replication_state'] = None __props__['type'] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_='azure-nextgen:sql:InstanceFailoverGroup'), pulumi.Alias(type_='azure-nextgen:sql/v20200202preview:InstanceFailoverGroup'), pulumi.Alias(type_='azure-nextgen:sql/v20200801preview:InstanceFailoverGroup')]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(InstanceFailoverGroup, __self__).__init__('azure-nextgen:sql/v20171001preview:InstanceFailoverGroup', resource_name, __props__, opts)
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]=None, failover_group_name: Optional[pulumi.Input[str]]=None, location_name: Optional[pulumi.Input[str]]=None, managed_instance_pairs: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ManagedInstancePairInfoArgs']]]]]=None, partner_regions: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['PartnerRegionInfoArgs']]]]]=None, read_only_endpoint: Optional[pulumi.Input[pulumi.InputType['InstanceFailoverGroupReadOnlyEndpointArgs']]]=None, read_write_endpoint: Optional[pulumi.Input[pulumi.InputType['InstanceFailoverGroupReadWriteEndpointArgs']]]=None, resource_group_name: Optional[pulumi.Input[str]]=None, __props__=None, __name__=None, __opts__=None): "\n An instance failover group.\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] failover_group_name: The name of the failover group.\n :param pulumi.Input[str] location_name: The name of the region where the resource is located.\n :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ManagedInstancePairInfoArgs']]]] managed_instance_pairs: List of managed instance pairs in the failover group.\n :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['PartnerRegionInfoArgs']]]] partner_regions: Partner region information for the failover group.\n :param pulumi.Input[pulumi.InputType['InstanceFailoverGroupReadOnlyEndpointArgs']] read_only_endpoint: Read-only endpoint of the failover group instance.\n :param pulumi.Input[pulumi.InputType['InstanceFailoverGroupReadWriteEndpointArgs']] read_write_endpoint: Read-write endpoint of the failover group instance.\n :param pulumi.Input[str] resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.\n " if (__name__ is not None): warnings.warn('explicit use of __name__ is deprecated', DeprecationWarning) resource_name = __name__ if (__opts__ is not None): warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if (opts is None): opts = pulumi.ResourceOptions() if (not isinstance(opts, pulumi.ResourceOptions)): raise TypeError('Expected resource options to be a ResourceOptions instance') if (opts.version is None): opts.version = _utilities.get_version() if (opts.id is None): if (__props__ is not None): raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['failover_group_name'] = failover_group_name if ((location_name is None) and (not opts.urn)): raise TypeError("Missing required property 'location_name'") __props__['location_name'] = location_name if ((managed_instance_pairs is None) and (not opts.urn)): raise TypeError("Missing required property 'managed_instance_pairs'") __props__['managed_instance_pairs'] = managed_instance_pairs if ((partner_regions is None) and (not opts.urn)): raise TypeError("Missing required property 'partner_regions'") __props__['partner_regions'] = partner_regions __props__['read_only_endpoint'] = read_only_endpoint if ((read_write_endpoint is None) and (not opts.urn)): raise TypeError("Missing required property 'read_write_endpoint'") __props__['read_write_endpoint'] = read_write_endpoint if ((resource_group_name is None) and (not opts.urn)): raise TypeError("Missing required property 'resource_group_name'") __props__['resource_group_name'] = resource_group_name __props__['name'] = None __props__['replication_role'] = None __props__['replication_state'] = None __props__['type'] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_='azure-nextgen:sql:InstanceFailoverGroup'), pulumi.Alias(type_='azure-nextgen:sql/v20200202preview:InstanceFailoverGroup'), pulumi.Alias(type_='azure-nextgen:sql/v20200801preview:InstanceFailoverGroup')]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(InstanceFailoverGroup, __self__).__init__('azure-nextgen:sql/v20171001preview:InstanceFailoverGroup', resource_name, __props__, opts)<|docstring|>An instance failover group. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] failover_group_name: The name of the failover group. :param pulumi.Input[str] location_name: The name of the region where the resource is located. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ManagedInstancePairInfoArgs']]]] managed_instance_pairs: List of managed instance pairs in the failover group. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['PartnerRegionInfoArgs']]]] partner_regions: Partner region information for the failover group. :param pulumi.Input[pulumi.InputType['InstanceFailoverGroupReadOnlyEndpointArgs']] read_only_endpoint: Read-only endpoint of the failover group instance. :param pulumi.Input[pulumi.InputType['InstanceFailoverGroupReadWriteEndpointArgs']] read_write_endpoint: Read-write endpoint of the failover group instance. :param pulumi.Input[str] resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.<|endoftext|>
f929b95e4bc20c9f0db5daa74f47ff3a7aeb2e9346531dc8c985fbf04a608b69
@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions]=None) -> 'InstanceFailoverGroup': "\n Get an existing InstanceFailoverGroup resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n " opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() return InstanceFailoverGroup(resource_name, opts=opts, __props__=__props__)
Get an existing InstanceFailoverGroup resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource.
sdk/python/pulumi_azure_nextgen/sql/v20171001preview/instance_failover_group.py
get
pulumi/pulumi-azure-nextgen
31
python
@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions]=None) -> 'InstanceFailoverGroup': "\n Get an existing InstanceFailoverGroup resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n " opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() return InstanceFailoverGroup(resource_name, opts=opts, __props__=__props__)
@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions]=None) -> 'InstanceFailoverGroup': "\n Get an existing InstanceFailoverGroup resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n " opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() return InstanceFailoverGroup(resource_name, opts=opts, __props__=__props__)<|docstring|>Get an existing InstanceFailoverGroup resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource.<|endoftext|>
7467b9f480f9ce47fab4879dcf308eb2a0cd76b1a71e405f6a87bf30b820c482
@property @pulumi.getter(name='managedInstancePairs') def managed_instance_pairs(self) -> pulumi.Output[Sequence['outputs.ManagedInstancePairInfoResponse']]: '\n List of managed instance pairs in the failover group.\n ' return pulumi.get(self, 'managed_instance_pairs')
List of managed instance pairs in the failover group.
sdk/python/pulumi_azure_nextgen/sql/v20171001preview/instance_failover_group.py
managed_instance_pairs
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter(name='managedInstancePairs') def managed_instance_pairs(self) -> pulumi.Output[Sequence['outputs.ManagedInstancePairInfoResponse']]: '\n \n ' return pulumi.get(self, 'managed_instance_pairs')
@property @pulumi.getter(name='managedInstancePairs') def managed_instance_pairs(self) -> pulumi.Output[Sequence['outputs.ManagedInstancePairInfoResponse']]: '\n \n ' return pulumi.get(self, 'managed_instance_pairs')<|docstring|>List of managed instance pairs in the failover group.<|endoftext|>
a4e4e82a2a3c7ece9d2d421b2e96b6188500f00a67c0b68eb10f134111e2eec7
@property @pulumi.getter def name(self) -> pulumi.Output[str]: '\n Resource name.\n ' return pulumi.get(self, 'name')
Resource name.
sdk/python/pulumi_azure_nextgen/sql/v20171001preview/instance_failover_group.py
name
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter def name(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'name')
@property @pulumi.getter def name(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'name')<|docstring|>Resource name.<|endoftext|>
f2fdf12d998491fbace8d1df33d08a278a8e29a012ba8b9c16561e3866f59744
@property @pulumi.getter(name='partnerRegions') def partner_regions(self) -> pulumi.Output[Sequence['outputs.PartnerRegionInfoResponse']]: '\n Partner region information for the failover group.\n ' return pulumi.get(self, 'partner_regions')
Partner region information for the failover group.
sdk/python/pulumi_azure_nextgen/sql/v20171001preview/instance_failover_group.py
partner_regions
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter(name='partnerRegions') def partner_regions(self) -> pulumi.Output[Sequence['outputs.PartnerRegionInfoResponse']]: '\n \n ' return pulumi.get(self, 'partner_regions')
@property @pulumi.getter(name='partnerRegions') def partner_regions(self) -> pulumi.Output[Sequence['outputs.PartnerRegionInfoResponse']]: '\n \n ' return pulumi.get(self, 'partner_regions')<|docstring|>Partner region information for the failover group.<|endoftext|>
d0440d92ba73ca12df27963577ea0bc06865cd3c9e879b6428ccb451b4ac5339
@property @pulumi.getter(name='readOnlyEndpoint') def read_only_endpoint(self) -> pulumi.Output[Optional['outputs.InstanceFailoverGroupReadOnlyEndpointResponse']]: '\n Read-only endpoint of the failover group instance.\n ' return pulumi.get(self, 'read_only_endpoint')
Read-only endpoint of the failover group instance.
sdk/python/pulumi_azure_nextgen/sql/v20171001preview/instance_failover_group.py
read_only_endpoint
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter(name='readOnlyEndpoint') def read_only_endpoint(self) -> pulumi.Output[Optional['outputs.InstanceFailoverGroupReadOnlyEndpointResponse']]: '\n \n ' return pulumi.get(self, 'read_only_endpoint')
@property @pulumi.getter(name='readOnlyEndpoint') def read_only_endpoint(self) -> pulumi.Output[Optional['outputs.InstanceFailoverGroupReadOnlyEndpointResponse']]: '\n \n ' return pulumi.get(self, 'read_only_endpoint')<|docstring|>Read-only endpoint of the failover group instance.<|endoftext|>
21dd3d35167bcfe1570ecb105c5d34bbc1cd4d7d8dddb3c512f222a57eb22456
@property @pulumi.getter(name='readWriteEndpoint') def read_write_endpoint(self) -> pulumi.Output['outputs.InstanceFailoverGroupReadWriteEndpointResponse']: '\n Read-write endpoint of the failover group instance.\n ' return pulumi.get(self, 'read_write_endpoint')
Read-write endpoint of the failover group instance.
sdk/python/pulumi_azure_nextgen/sql/v20171001preview/instance_failover_group.py
read_write_endpoint
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter(name='readWriteEndpoint') def read_write_endpoint(self) -> pulumi.Output['outputs.InstanceFailoverGroupReadWriteEndpointResponse']: '\n \n ' return pulumi.get(self, 'read_write_endpoint')
@property @pulumi.getter(name='readWriteEndpoint') def read_write_endpoint(self) -> pulumi.Output['outputs.InstanceFailoverGroupReadWriteEndpointResponse']: '\n \n ' return pulumi.get(self, 'read_write_endpoint')<|docstring|>Read-write endpoint of the failover group instance.<|endoftext|>
2a9e05cec798422093606c44eeeba8836287e4ec650b8ef793f8e2ab8f6a49d1
@property @pulumi.getter(name='replicationRole') def replication_role(self) -> pulumi.Output[str]: '\n Local replication role of the failover group instance.\n ' return pulumi.get(self, 'replication_role')
Local replication role of the failover group instance.
sdk/python/pulumi_azure_nextgen/sql/v20171001preview/instance_failover_group.py
replication_role
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter(name='replicationRole') def replication_role(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'replication_role')
@property @pulumi.getter(name='replicationRole') def replication_role(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'replication_role')<|docstring|>Local replication role of the failover group instance.<|endoftext|>
d7bf828a04fcbc8456ae85de3cef929d7759863bdabcbafccea9a3ccabf48413
@property @pulumi.getter(name='replicationState') def replication_state(self) -> pulumi.Output[str]: '\n Replication state of the failover group instance.\n ' return pulumi.get(self, 'replication_state')
Replication state of the failover group instance.
sdk/python/pulumi_azure_nextgen/sql/v20171001preview/instance_failover_group.py
replication_state
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter(name='replicationState') def replication_state(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'replication_state')
@property @pulumi.getter(name='replicationState') def replication_state(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'replication_state')<|docstring|>Replication state of the failover group instance.<|endoftext|>
c15c1dc56245d583a9bb3efd3c3335f1e16831d01076e7f735161462641f2693
@property @pulumi.getter def type(self) -> pulumi.Output[str]: '\n Resource type.\n ' return pulumi.get(self, 'type')
Resource type.
sdk/python/pulumi_azure_nextgen/sql/v20171001preview/instance_failover_group.py
type
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter def type(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'type')
@property @pulumi.getter def type(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'type')<|docstring|>Resource type.<|endoftext|>
4c6b31f42c383dae19a2439d72761f961e7eb8f8506d6f749f55ff3a6b50677c
def divide(self, dividend: int, divisor: int) -> int: '\n Main method of this module.\n :param dividend:\n :param divisor:\n :return:\n ' negative = False if ((dividend >= 0) and (divisor >= 0)): negative = False elif ((dividend < 0) and (divisor >= 0)): negative = True elif ((dividend > 0) and (divisor <= 0)): negative = True (abs_dividend, abs_divisor) = (abs(dividend), abs(divisor)) if (abs_divisor == 1): if (negative == True): return ((- abs_dividend) if (Solution.MIN_INT < (- abs_dividend)) else Solution.MIN_INT) else: return (abs_dividend if (Solution.MAX_INT > abs_dividend) else Solution.MAX_INT) q = self.recursive_divide(abs_dividend, abs_divisor) return (q if (negative == False) else (- q))
Main method of this module. :param dividend: :param divisor: :return:
integer-division/solution.py
divide
playandlearntocode/general-purpose-algorithms
2
python
def divide(self, dividend: int, divisor: int) -> int: '\n Main method of this module.\n :param dividend:\n :param divisor:\n :return:\n ' negative = False if ((dividend >= 0) and (divisor >= 0)): negative = False elif ((dividend < 0) and (divisor >= 0)): negative = True elif ((dividend > 0) and (divisor <= 0)): negative = True (abs_dividend, abs_divisor) = (abs(dividend), abs(divisor)) if (abs_divisor == 1): if (negative == True): return ((- abs_dividend) if (Solution.MIN_INT < (- abs_dividend)) else Solution.MIN_INT) else: return (abs_dividend if (Solution.MAX_INT > abs_dividend) else Solution.MAX_INT) q = self.recursive_divide(abs_dividend, abs_divisor) return (q if (negative == False) else (- q))
def divide(self, dividend: int, divisor: int) -> int: '\n Main method of this module.\n :param dividend:\n :param divisor:\n :return:\n ' negative = False if ((dividend >= 0) and (divisor >= 0)): negative = False elif ((dividend < 0) and (divisor >= 0)): negative = True elif ((dividend > 0) and (divisor <= 0)): negative = True (abs_dividend, abs_divisor) = (abs(dividend), abs(divisor)) if (abs_divisor == 1): if (negative == True): return ((- abs_dividend) if (Solution.MIN_INT < (- abs_dividend)) else Solution.MIN_INT) else: return (abs_dividend if (Solution.MAX_INT > abs_dividend) else Solution.MAX_INT) q = self.recursive_divide(abs_dividend, abs_divisor) return (q if (negative == False) else (- q))<|docstring|>Main method of this module. :param dividend: :param divisor: :return:<|endoftext|>
af2c362feb2f92c68d0d8a885a0190a2a5be0eb314bbf20a661ea705182e942b
@exec_time def readDataSet(self): '\n\n self.csv_path : csv -file was made by excel export.It can contain data on many characteristics. For time series ,\n we need data about date and time and actual data about some feature, like as Imbalance in the\n power grid. If we consider cvs-dataset as a matrix, then the first row or header contains the\n names of the columns. The samples must de equidistance\n self.dt_dset: name of date/time column\n self.rcpower_dset:name of actual characteristic.\n self.discret : discretization, this used for logging\n self.f : log file handler\n :return: df -pandas DataFrame object\n ' self.df = pd.read_csv(self.csv_path) self.df.head() self.df[self.rcpower_dset] = pd.to_numeric(self.df[self.rcpower_dset], errors='coerce') self.df = self.df.dropna(subset=[self.rcpower_dset]) self.df[self.dt_dset] = pd.to_datetime(self.df[self.dt_dset], dayfirst=True) self.df = self.df.loc[(:, [self.dt_dset, self.rcpower_dset])] self.df.sort_values(self.dt_dset, inplace=True, ascending=True) self.df = self.df.reset_index(drop=True) self.df[self.rcpower_dset] *= self.simple_scale self.df[self.rcpower_dset] += self.simple_bias self.df.info() self.df.head(10) title = 'Number of rows and columns after removing missing values' tsBoundaries2log(title, self.df, self.dt_dset, self.rcpower_dset, self.f) return
self.csv_path : csv -file was made by excel export.It can contain data on many characteristics. For time series , we need data about date and time and actual data about some feature, like as Imbalance in the power grid. If we consider cvs-dataset as a matrix, then the first row or header contains the names of the columns. The samples must de equidistance self.dt_dset: name of date/time column self.rcpower_dset:name of actual characteristic. self.discret : discretization, this used for logging self.f : log file handler :return: df -pandas DataFrame object
stgelpDL/predictor/dataset.py
readDataSet
dmitryv56/stgelpDL
0
python
@exec_time def readDataSet(self): '\n\n self.csv_path : csv -file was made by excel export.It can contain data on many characteristics. For time series ,\n we need data about date and time and actual data about some feature, like as Imbalance in the\n power grid. If we consider cvs-dataset as a matrix, then the first row or header contains the\n names of the columns. The samples must de equidistance\n self.dt_dset: name of date/time column\n self.rcpower_dset:name of actual characteristic.\n self.discret : discretization, this used for logging\n self.f : log file handler\n :return: df -pandas DataFrame object\n ' self.df = pd.read_csv(self.csv_path) self.df.head() self.df[self.rcpower_dset] = pd.to_numeric(self.df[self.rcpower_dset], errors='coerce') self.df = self.df.dropna(subset=[self.rcpower_dset]) self.df[self.dt_dset] = pd.to_datetime(self.df[self.dt_dset], dayfirst=True) self.df = self.df.loc[(:, [self.dt_dset, self.rcpower_dset])] self.df.sort_values(self.dt_dset, inplace=True, ascending=True) self.df = self.df.reset_index(drop=True) self.df[self.rcpower_dset] *= self.simple_scale self.df[self.rcpower_dset] += self.simple_bias self.df.info() self.df.head(10) title = 'Number of rows and columns after removing missing values' tsBoundaries2log(title, self.df, self.dt_dset, self.rcpower_dset, self.f) return
@exec_time def readDataSet(self): '\n\n self.csv_path : csv -file was made by excel export.It can contain data on many characteristics. For time series ,\n we need data about date and time and actual data about some feature, like as Imbalance in the\n power grid. If we consider cvs-dataset as a matrix, then the first row or header contains the\n names of the columns. The samples must de equidistance\n self.dt_dset: name of date/time column\n self.rcpower_dset:name of actual characteristic.\n self.discret : discretization, this used for logging\n self.f : log file handler\n :return: df -pandas DataFrame object\n ' self.df = pd.read_csv(self.csv_path) self.df.head() self.df[self.rcpower_dset] = pd.to_numeric(self.df[self.rcpower_dset], errors='coerce') self.df = self.df.dropna(subset=[self.rcpower_dset]) self.df[self.dt_dset] = pd.to_datetime(self.df[self.dt_dset], dayfirst=True) self.df = self.df.loc[(:, [self.dt_dset, self.rcpower_dset])] self.df.sort_values(self.dt_dset, inplace=True, ascending=True) self.df = self.df.reset_index(drop=True) self.df[self.rcpower_dset] *= self.simple_scale self.df[self.rcpower_dset] += self.simple_bias self.df.info() self.df.head(10) title = 'Number of rows and columns after removing missing values' tsBoundaries2log(title, self.df, self.dt_dset, self.rcpower_dset, self.f) return<|docstring|>self.csv_path : csv -file was made by excel export.It can contain data on many characteristics. For time series , we need data about date and time and actual data about some feature, like as Imbalance in the power grid. If we consider cvs-dataset as a matrix, then the first row or header contains the names of the columns. The samples must de equidistance self.dt_dset: name of date/time column self.rcpower_dset:name of actual characteristic. self.discret : discretization, this used for logging self.f : log file handler :return: df -pandas DataFrame object<|endoftext|>
71d5a4fe6f0846231b032b0f637492af76c33d62d6f322d59669bae0442a37a3
@exec_time def set_train_val_test_sequence(self): '\n\n self.df: DataFrame object\n self.dt_dset: - date/time header name, i.e. "Date Time"\n self.rcpower_dset: - actual characteristic header name, i.e. "Imbalance"\n self.test_cut_off: - value to pass time delta value in the \'minutes\' resolution or None, like as\n \'minutes=<value>.\' NOte: the timedelta () function does not accept string as parameter, but\n as value timedelta(minutes=value)\n The last sampled values before time cutoff represent the test sequence.\n self.val_cut_off: - value to pass time delta value in the \'minutes\' resolution or None, like as\n \'minutes=<value>.\'\n The last sampled values before the test sequence.\n\n self.f: - log file hadler\n :return:\n ' if ((self.test_cut_off is None) or (self.test_cut_off == '')): test_cutoff_date = self.df[self.dt_dset].max() self.df_test = None else: test_cutoff_date = (self.df[self.dt_dset].max() - timedelta(minutes=self.test_cut_off)) self.df_test = self.df[(self.df[self.dt_dset] > test_cutoff_date)] if ((self.val_cut_off is None) or (self.val_cut_off == '')): self.df_val = None else: val_cutoff_date = (test_cutoff_date - timedelta(minutes=self.val_cut_off)) self.df_val = self.df[((self.df[self.dt_dset] > val_cutoff_date) & (self.df[self.dt_dset] <= test_cutoff_date))] self.df_train = self.df[(self.df[self.dt_dset] <= val_cutoff_date)] tsSubset2log(self.dt_dset, self.rcpower_dset, self.df_train, self.df_val, self.df_test, self.f) datePredict = self.df_test[self.dt_dset].values[0] actvalPredict = self.df_test[self.rcpower_dset].values[0] return (datePredict, actvalPredict)
self.df: DataFrame object self.dt_dset: - date/time header name, i.e. "Date Time" self.rcpower_dset: - actual characteristic header name, i.e. "Imbalance" self.test_cut_off: - value to pass time delta value in the 'minutes' resolution or None, like as 'minutes=<value>.' NOte: the timedelta () function does not accept string as parameter, but as value timedelta(minutes=value) The last sampled values before time cutoff represent the test sequence. self.val_cut_off: - value to pass time delta value in the 'minutes' resolution or None, like as 'minutes=<value>.' The last sampled values before the test sequence. self.f: - log file hadler :return:
stgelpDL/predictor/dataset.py
set_train_val_test_sequence
dmitryv56/stgelpDL
0
python
@exec_time def set_train_val_test_sequence(self): '\n\n self.df: DataFrame object\n self.dt_dset: - date/time header name, i.e. "Date Time"\n self.rcpower_dset: - actual characteristic header name, i.e. "Imbalance"\n self.test_cut_off: - value to pass time delta value in the \'minutes\' resolution or None, like as\n \'minutes=<value>.\' NOte: the timedelta () function does not accept string as parameter, but\n as value timedelta(minutes=value)\n The last sampled values before time cutoff represent the test sequence.\n self.val_cut_off: - value to pass time delta value in the \'minutes\' resolution or None, like as\n \'minutes=<value>.\'\n The last sampled values before the test sequence.\n\n self.f: - log file hadler\n :return:\n ' if ((self.test_cut_off is None) or (self.test_cut_off == )): test_cutoff_date = self.df[self.dt_dset].max() self.df_test = None else: test_cutoff_date = (self.df[self.dt_dset].max() - timedelta(minutes=self.test_cut_off)) self.df_test = self.df[(self.df[self.dt_dset] > test_cutoff_date)] if ((self.val_cut_off is None) or (self.val_cut_off == )): self.df_val = None else: val_cutoff_date = (test_cutoff_date - timedelta(minutes=self.val_cut_off)) self.df_val = self.df[((self.df[self.dt_dset] > val_cutoff_date) & (self.df[self.dt_dset] <= test_cutoff_date))] self.df_train = self.df[(self.df[self.dt_dset] <= val_cutoff_date)] tsSubset2log(self.dt_dset, self.rcpower_dset, self.df_train, self.df_val, self.df_test, self.f) datePredict = self.df_test[self.dt_dset].values[0] actvalPredict = self.df_test[self.rcpower_dset].values[0] return (datePredict, actvalPredict)
@exec_time def set_train_val_test_sequence(self): '\n\n self.df: DataFrame object\n self.dt_dset: - date/time header name, i.e. "Date Time"\n self.rcpower_dset: - actual characteristic header name, i.e. "Imbalance"\n self.test_cut_off: - value to pass time delta value in the \'minutes\' resolution or None, like as\n \'minutes=<value>.\' NOte: the timedelta () function does not accept string as parameter, but\n as value timedelta(minutes=value)\n The last sampled values before time cutoff represent the test sequence.\n self.val_cut_off: - value to pass time delta value in the \'minutes\' resolution or None, like as\n \'minutes=<value>.\'\n The last sampled values before the test sequence.\n\n self.f: - log file hadler\n :return:\n ' if ((self.test_cut_off is None) or (self.test_cut_off == )): test_cutoff_date = self.df[self.dt_dset].max() self.df_test = None else: test_cutoff_date = (self.df[self.dt_dset].max() - timedelta(minutes=self.test_cut_off)) self.df_test = self.df[(self.df[self.dt_dset] > test_cutoff_date)] if ((self.val_cut_off is None) or (self.val_cut_off == )): self.df_val = None else: val_cutoff_date = (test_cutoff_date - timedelta(minutes=self.val_cut_off)) self.df_val = self.df[((self.df[self.dt_dset] > val_cutoff_date) & (self.df[self.dt_dset] <= test_cutoff_date))] self.df_train = self.df[(self.df[self.dt_dset] <= val_cutoff_date)] tsSubset2log(self.dt_dset, self.rcpower_dset, self.df_train, self.df_val, self.df_test, self.f) datePredict = self.df_test[self.dt_dset].values[0] actvalPredict = self.df_test[self.rcpower_dset].values[0] return (datePredict, actvalPredict)<|docstring|>self.df: DataFrame object self.dt_dset: - date/time header name, i.e. "Date Time" self.rcpower_dset: - actual characteristic header name, i.e. "Imbalance" self.test_cut_off: - value to pass time delta value in the 'minutes' resolution or None, like as 'minutes=<value>.' NOte: the timedelta () function does not accept string as parameter, but as value timedelta(minutes=value) The last sampled values before time cutoff represent the test sequence. self.val_cut_off: - value to pass time delta value in the 'minutes' resolution or None, like as 'minutes=<value>.' The last sampled values before the test sequence. self.f: - log file hadler :return:<|endoftext|>
93f1107202b5844c7305ffe4b4f8a49a05a4313c12471ecc29fa0b5525c44725
def testResultDone(self): 'Tests that last_result is marked `done` after trial is complete.' ray.init(num_cpus=1, num_gpus=1) runner = TrialRunner() kwargs = {'stopping_criterion': {'training_iteration': 2}, 'resources': Resources(cpu=1, gpu=1)} runner.add_trial(Trial('__fake', **kwargs)) trials = runner.get_trials() runner.step() self.assertEqual(trials[0].status, Trial.RUNNING) runner.step() self.assertNotEqual(trials[0].last_result.done, True) runner.step() self.assertEqual(trials[0].last_result.done, True)
Tests that last_result is marked `done` after trial is complete.
python/ray/tune/test/trial_runner_test.py
testResultDone
smkuls/ray
0
python
def testResultDone(self): ray.init(num_cpus=1, num_gpus=1) runner = TrialRunner() kwargs = {'stopping_criterion': {'training_iteration': 2}, 'resources': Resources(cpu=1, gpu=1)} runner.add_trial(Trial('__fake', **kwargs)) trials = runner.get_trials() runner.step() self.assertEqual(trials[0].status, Trial.RUNNING) runner.step() self.assertNotEqual(trials[0].last_result.done, True) runner.step() self.assertEqual(trials[0].last_result.done, True)
def testResultDone(self): ray.init(num_cpus=1, num_gpus=1) runner = TrialRunner() kwargs = {'stopping_criterion': {'training_iteration': 2}, 'resources': Resources(cpu=1, gpu=1)} runner.add_trial(Trial('__fake', **kwargs)) trials = runner.get_trials() runner.step() self.assertEqual(trials[0].status, Trial.RUNNING) runner.step() self.assertNotEqual(trials[0].last_result.done, True) runner.step() self.assertEqual(trials[0].last_result.done, True)<|docstring|>Tests that last_result is marked `done` after trial is complete.<|endoftext|>
69a7cae79b6832f3bbd1c920b4a4d144d2be08ff61415965bc90a600975bb793
def set_keywords(self, keywords): 'Setter for keywords.' if (keywords is None): self.keywords = None else: self.keywords = [] keywords = (keywords if isinstance(keywords, list) else [keywords]) for kw in keywords: if isinstance(kw, str): self.keywords.append(str.lower(str.strip(kw))) else: self.keywords.append(kw)
Setter for keywords.
ccollab2eeplatform/filters/product_filter.py
set_keywords
CVBDL/ccollab2eeplatform-python
0
python
def set_keywords(self, keywords): if (keywords is None): self.keywords = None else: self.keywords = [] keywords = (keywords if isinstance(keywords, list) else [keywords]) for kw in keywords: if isinstance(kw, str): self.keywords.append(str.lower(str.strip(kw))) else: self.keywords.append(kw)
def set_keywords(self, keywords): if (keywords is None): self.keywords = None else: self.keywords = [] keywords = (keywords if isinstance(keywords, list) else [keywords]) for kw in keywords: if isinstance(kw, str): self.keywords.append(str.lower(str.strip(kw))) else: self.keywords.append(kw)<|docstring|>Setter for keywords.<|endoftext|>
1267365546973f2fcd7fef9a6df1a683142c17ef8e738b85663bc8d8f3feaba5
def filter(self): 'Filter function.\n\n Returns:\n Filtered records list. None if error occurred.\n If keyword is None or empty list, then returns all records.\n ' if ((not self.records) or (not self.keywords)): return self.records try: result_iterator = filterfalse((lambda record: (not (record.creator_product_name in self.keywords))), self.records) return list(result_iterator) except AttributeError: return None
Filter function. Returns: Filtered records list. None if error occurred. If keyword is None or empty list, then returns all records.
ccollab2eeplatform/filters/product_filter.py
filter
CVBDL/ccollab2eeplatform-python
0
python
def filter(self): 'Filter function.\n\n Returns:\n Filtered records list. None if error occurred.\n If keyword is None or empty list, then returns all records.\n ' if ((not self.records) or (not self.keywords)): return self.records try: result_iterator = filterfalse((lambda record: (not (record.creator_product_name in self.keywords))), self.records) return list(result_iterator) except AttributeError: return None
def filter(self): 'Filter function.\n\n Returns:\n Filtered records list. None if error occurred.\n If keyword is None or empty list, then returns all records.\n ' if ((not self.records) or (not self.keywords)): return self.records try: result_iterator = filterfalse((lambda record: (not (record.creator_product_name in self.keywords))), self.records) return list(result_iterator) except AttributeError: return None<|docstring|>Filter function. Returns: Filtered records list. None if error occurred. If keyword is None or empty list, then returns all records.<|endoftext|>
5fedf3c9d0a610e79c1d68a1317d2beb57d01f2eaad9f0ecf660687ec6a21c3c
def test_input_error(): 'Check TypeError raised when the input is not string' with pytest.raises(TypeError): try_num = 111 animalClassifier(try_num)
Check TypeError raised when the input is not string
tests/test_animalClassifier.py
test_input_error
UBC-MDS/animalsgonewild
1
python
def test_input_error(): with pytest.raises(TypeError): try_num = 111 animalClassifier(try_num)
def test_input_error(): with pytest.raises(TypeError): try_num = 111 animalClassifier(try_num)<|docstring|>Check TypeError raised when the input is not string<|endoftext|>
2bfd44474a80b36c93c3f3a4319407c5a26355eb1d747d3e6d8599c87ca4a8a4
def conv3x3(in_planes: int, out_planes: int, stride: int=1) -> nn.Module: '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
3x3 convolution with padding
mseg_semantic/model/seg_hrnet.py
conv3x3
Shawn207/mseg-semantic
0
python
def conv3x3(in_planes: int, out_planes: int, stride: int=1) -> nn.Module: return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
def conv3x3(in_planes: int, out_planes: int, stride: int=1) -> nn.Module: return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)<|docstring|>3x3 convolution with padding<|endoftext|>
3a51771d95752b124417fadbbe45ffb26109435097db78dc9143a4562d19eff0
def get_configured_hrnet(n_classes: int, load_imagenet_model: bool=False, imagenet_ckpt_fpath: str='') -> nn.Module: '\n Args:\n n_classes: integer representing number of output classes.\n load_imagenet_model: whether to initialize from ImageNet-pretrained model.\n imagenet_ckpt_fpath: string representing path to file with weights to\n initialize model with.\n\n Returns:\n model: HRNet model w/ architecture configured according to model yaml,\n and with specified number of classes and weights initialized\n (at training, init using imagenet-pretrained model).\n ' with hydra.initialize_config_module(config_module='mseg_semantic.model'): cfg = hydra.compose(config_name='seg_hrnet.yaml') logger.info('Using config: ') logger.info(OmegaConf.to_yaml(cfg)) config: HRNetArchConfig = instantiate(cfg.HRNetArchConfig) criterion = nn.CrossEntropyLoss(ignore_index=255) model = get_seg_model(config, criterion, n_classes, load_imagenet_model, imagenet_ckpt_fpath) return model
Args: n_classes: integer representing number of output classes. load_imagenet_model: whether to initialize from ImageNet-pretrained model. imagenet_ckpt_fpath: string representing path to file with weights to initialize model with. Returns: model: HRNet model w/ architecture configured according to model yaml, and with specified number of classes and weights initialized (at training, init using imagenet-pretrained model).
mseg_semantic/model/seg_hrnet.py
get_configured_hrnet
Shawn207/mseg-semantic
0
python
def get_configured_hrnet(n_classes: int, load_imagenet_model: bool=False, imagenet_ckpt_fpath: str=) -> nn.Module: '\n Args:\n n_classes: integer representing number of output classes.\n load_imagenet_model: whether to initialize from ImageNet-pretrained model.\n imagenet_ckpt_fpath: string representing path to file with weights to\n initialize model with.\n\n Returns:\n model: HRNet model w/ architecture configured according to model yaml,\n and with specified number of classes and weights initialized\n (at training, init using imagenet-pretrained model).\n ' with hydra.initialize_config_module(config_module='mseg_semantic.model'): cfg = hydra.compose(config_name='seg_hrnet.yaml') logger.info('Using config: ') logger.info(OmegaConf.to_yaml(cfg)) config: HRNetArchConfig = instantiate(cfg.HRNetArchConfig) criterion = nn.CrossEntropyLoss(ignore_index=255) model = get_seg_model(config, criterion, n_classes, load_imagenet_model, imagenet_ckpt_fpath) return model
def get_configured_hrnet(n_classes: int, load_imagenet_model: bool=False, imagenet_ckpt_fpath: str=) -> nn.Module: '\n Args:\n n_classes: integer representing number of output classes.\n load_imagenet_model: whether to initialize from ImageNet-pretrained model.\n imagenet_ckpt_fpath: string representing path to file with weights to\n initialize model with.\n\n Returns:\n model: HRNet model w/ architecture configured according to model yaml,\n and with specified number of classes and weights initialized\n (at training, init using imagenet-pretrained model).\n ' with hydra.initialize_config_module(config_module='mseg_semantic.model'): cfg = hydra.compose(config_name='seg_hrnet.yaml') logger.info('Using config: ') logger.info(OmegaConf.to_yaml(cfg)) config: HRNetArchConfig = instantiate(cfg.HRNetArchConfig) criterion = nn.CrossEntropyLoss(ignore_index=255) model = get_seg_model(config, criterion, n_classes, load_imagenet_model, imagenet_ckpt_fpath) return model<|docstring|>Args: n_classes: integer representing number of output classes. load_imagenet_model: whether to initialize from ImageNet-pretrained model. imagenet_ckpt_fpath: string representing path to file with weights to initialize model with. Returns: model: HRNet model w/ architecture configured according to model yaml, and with specified number of classes and weights initialized (at training, init using imagenet-pretrained model).<|endoftext|>
bf3bcc215040cbcf1bb8718bd4e4525364bd9f834ca057d93a8bbffcbfbf4647
def forward(self, x: List[torch.Tensor]) -> List[torch.Tensor]: '\n Args:\n x: list of Pytorch tensors.\n\n Returns:\n x_fuse: list of Pytorch tensors.\n ' if (self.num_branches == 1): return [self.branches[0](x[0])] for i in range(self.num_branches): x[i] = self.branches[i](x[i]) x_fuse = [] for i in range(len(self.fuse_layers)): y = (x[0] if (i == 0) else self.fuse_layers[i][0](x[0])) for j in range(1, self.num_branches): if (i == j): y = (y + x[j]) elif (j > i): width_output = x[i].shape[(- 1)] height_output = x[i].shape[(- 2)] y = (y + F.interpolate(self.fuse_layers[i][j](x[j]), size=[height_output, width_output], mode='bilinear')) else: y = (y + self.fuse_layers[i][j](x[j])) x_fuse.append(self.relu(y)) return x_fuse
Args: x: list of Pytorch tensors. Returns: x_fuse: list of Pytorch tensors.
mseg_semantic/model/seg_hrnet.py
forward
Shawn207/mseg-semantic
0
python
def forward(self, x: List[torch.Tensor]) -> List[torch.Tensor]: '\n Args:\n x: list of Pytorch tensors.\n\n Returns:\n x_fuse: list of Pytorch tensors.\n ' if (self.num_branches == 1): return [self.branches[0](x[0])] for i in range(self.num_branches): x[i] = self.branches[i](x[i]) x_fuse = [] for i in range(len(self.fuse_layers)): y = (x[0] if (i == 0) else self.fuse_layers[i][0](x[0])) for j in range(1, self.num_branches): if (i == j): y = (y + x[j]) elif (j > i): width_output = x[i].shape[(- 1)] height_output = x[i].shape[(- 2)] y = (y + F.interpolate(self.fuse_layers[i][j](x[j]), size=[height_output, width_output], mode='bilinear')) else: y = (y + self.fuse_layers[i][j](x[j])) x_fuse.append(self.relu(y)) return x_fuse
def forward(self, x: List[torch.Tensor]) -> List[torch.Tensor]: '\n Args:\n x: list of Pytorch tensors.\n\n Returns:\n x_fuse: list of Pytorch tensors.\n ' if (self.num_branches == 1): return [self.branches[0](x[0])] for i in range(self.num_branches): x[i] = self.branches[i](x[i]) x_fuse = [] for i in range(len(self.fuse_layers)): y = (x[0] if (i == 0) else self.fuse_layers[i][0](x[0])) for j in range(1, self.num_branches): if (i == j): y = (y + x[j]) elif (j > i): width_output = x[i].shape[(- 1)] height_output = x[i].shape[(- 2)] y = (y + F.interpolate(self.fuse_layers[i][j](x[j]), size=[height_output, width_output], mode='bilinear')) else: y = (y + self.fuse_layers[i][j](x[j])) x_fuse.append(self.relu(y)) return x_fuse<|docstring|>Args: x: list of Pytorch tensors. Returns: x_fuse: list of Pytorch tensors.<|endoftext|>
d7a3d62ebd9955bd48f2b75dcdc75856857d6174821c5c06773628ee41b50456
def _make_transition_layer(self, num_channels_pre_layer: List[int], num_channels_cur_layer: List[int]) -> nn.ModuleList: '\n Use 3x3 convolutions, with stride 2 and padding 1.\n ' num_branches_cur = len(num_channels_cur_layer) num_branches_pre = len(num_channels_pre_layer) transition_layers = [] for i in range(num_branches_cur): if (i < num_branches_pre): if (num_channels_cur_layer[i] != num_channels_pre_layer[i]): transition_layers.append(nn.Sequential(nn.Conv2d(num_channels_pre_layer[i], num_channels_cur_layer[i], 3, 1, 1, bias=False), BatchNorm2d(num_channels_cur_layer[i], momentum=BN_MOMENTUM), nn.ReLU(inplace=True))) else: transition_layers.append(None) else: conv3x3s = [] for j in range(((i + 1) - num_branches_pre)): inchannels = num_channels_pre_layer[(- 1)] outchannels = (num_channels_cur_layer[i] if (j == (i - num_branches_pre)) else inchannels) conv3x3s.append(nn.Sequential(nn.Conv2d(inchannels, outchannels, 3, 2, 1, bias=False), BatchNorm2d(outchannels, momentum=BN_MOMENTUM), nn.ReLU(inplace=True))) transition_layers.append(nn.Sequential(*conv3x3s)) return nn.ModuleList(transition_layers)
Use 3x3 convolutions, with stride 2 and padding 1.
mseg_semantic/model/seg_hrnet.py
_make_transition_layer
Shawn207/mseg-semantic
0
python
def _make_transition_layer(self, num_channels_pre_layer: List[int], num_channels_cur_layer: List[int]) -> nn.ModuleList: '\n \n ' num_branches_cur = len(num_channels_cur_layer) num_branches_pre = len(num_channels_pre_layer) transition_layers = [] for i in range(num_branches_cur): if (i < num_branches_pre): if (num_channels_cur_layer[i] != num_channels_pre_layer[i]): transition_layers.append(nn.Sequential(nn.Conv2d(num_channels_pre_layer[i], num_channels_cur_layer[i], 3, 1, 1, bias=False), BatchNorm2d(num_channels_cur_layer[i], momentum=BN_MOMENTUM), nn.ReLU(inplace=True))) else: transition_layers.append(None) else: conv3x3s = [] for j in range(((i + 1) - num_branches_pre)): inchannels = num_channels_pre_layer[(- 1)] outchannels = (num_channels_cur_layer[i] if (j == (i - num_branches_pre)) else inchannels) conv3x3s.append(nn.Sequential(nn.Conv2d(inchannels, outchannels, 3, 2, 1, bias=False), BatchNorm2d(outchannels, momentum=BN_MOMENTUM), nn.ReLU(inplace=True))) transition_layers.append(nn.Sequential(*conv3x3s)) return nn.ModuleList(transition_layers)
def _make_transition_layer(self, num_channels_pre_layer: List[int], num_channels_cur_layer: List[int]) -> nn.ModuleList: '\n \n ' num_branches_cur = len(num_channels_cur_layer) num_branches_pre = len(num_channels_pre_layer) transition_layers = [] for i in range(num_branches_cur): if (i < num_branches_pre): if (num_channels_cur_layer[i] != num_channels_pre_layer[i]): transition_layers.append(nn.Sequential(nn.Conv2d(num_channels_pre_layer[i], num_channels_cur_layer[i], 3, 1, 1, bias=False), BatchNorm2d(num_channels_cur_layer[i], momentum=BN_MOMENTUM), nn.ReLU(inplace=True))) else: transition_layers.append(None) else: conv3x3s = [] for j in range(((i + 1) - num_branches_pre)): inchannels = num_channels_pre_layer[(- 1)] outchannels = (num_channels_cur_layer[i] if (j == (i - num_branches_pre)) else inchannels) conv3x3s.append(nn.Sequential(nn.Conv2d(inchannels, outchannels, 3, 2, 1, bias=False), BatchNorm2d(outchannels, momentum=BN_MOMENTUM), nn.ReLU(inplace=True))) transition_layers.append(nn.Sequential(*conv3x3s)) return nn.ModuleList(transition_layers)<|docstring|>Use 3x3 convolutions, with stride 2 and padding 1.<|endoftext|>
db7e60680b7c606a3c8afc88fb8887fabb898385bc4484fcecf059fbea7763cc
def _make_layer(self, block: Union[(BasicBlock, Bottleneck)], inplanes: int, planes: int, blocks: int, stride: int=1) -> nn.Module: '\n Identical to ResNet `_make_layer()`, except `inplanes` is an\n explicit argument rather than class attribute, and batch norm\n implementation and momentum are hardcoded.\n ' downsample = None if ((stride != 1) or (inplanes != (planes * block.expansion))): downsample = nn.Sequential(nn.Conv2d(inplanes, (planes * block.expansion), kernel_size=1, stride=stride, bias=False), BatchNorm2d((planes * block.expansion), momentum=BN_MOMENTUM)) layers = [] layers.append(block(inplanes, planes, stride, downsample)) inplanes = (planes * block.expansion) for i in range(1, blocks): layers.append(block(inplanes, planes)) return nn.Sequential(*layers)
Identical to ResNet `_make_layer()`, except `inplanes` is an explicit argument rather than class attribute, and batch norm implementation and momentum are hardcoded.
mseg_semantic/model/seg_hrnet.py
_make_layer
Shawn207/mseg-semantic
0
python
def _make_layer(self, block: Union[(BasicBlock, Bottleneck)], inplanes: int, planes: int, blocks: int, stride: int=1) -> nn.Module: '\n Identical to ResNet `_make_layer()`, except `inplanes` is an\n explicit argument rather than class attribute, and batch norm\n implementation and momentum are hardcoded.\n ' downsample = None if ((stride != 1) or (inplanes != (planes * block.expansion))): downsample = nn.Sequential(nn.Conv2d(inplanes, (planes * block.expansion), kernel_size=1, stride=stride, bias=False), BatchNorm2d((planes * block.expansion), momentum=BN_MOMENTUM)) layers = [] layers.append(block(inplanes, planes, stride, downsample)) inplanes = (planes * block.expansion) for i in range(1, blocks): layers.append(block(inplanes, planes)) return nn.Sequential(*layers)
def _make_layer(self, block: Union[(BasicBlock, Bottleneck)], inplanes: int, planes: int, blocks: int, stride: int=1) -> nn.Module: '\n Identical to ResNet `_make_layer()`, except `inplanes` is an\n explicit argument rather than class attribute, and batch norm\n implementation and momentum are hardcoded.\n ' downsample = None if ((stride != 1) or (inplanes != (planes * block.expansion))): downsample = nn.Sequential(nn.Conv2d(inplanes, (planes * block.expansion), kernel_size=1, stride=stride, bias=False), BatchNorm2d((planes * block.expansion), momentum=BN_MOMENTUM)) layers = [] layers.append(block(inplanes, planes, stride, downsample)) inplanes = (planes * block.expansion) for i in range(1, blocks): layers.append(block(inplanes, planes)) return nn.Sequential(*layers)<|docstring|>Identical to ResNet `_make_layer()`, except `inplanes` is an explicit argument rather than class attribute, and batch norm implementation and momentum are hardcoded.<|endoftext|>
f717b0e0d32558cdc758ff4c6e14db80f7ddb8a1fa29dc734415964ab52b87a8
def forward(self, x: torch.Tensor, y: Optional[torch.Tensor]=None): '\n Network starts from a stem of two strided 3 × 3 convolutions\n decreasing the resolution to 1/4.\n\n Rescale the low-resolution representations through bilinear\n upsampling to the high resolution, and concatenate the subsets\n of such representations.\n\n At end, the segmentation maps are upsampled (4 times) to the\n input size by bilinear upsampling for both training and testing.\n ' x_size = x.size() assert ((((x_size[2] - 1) % 8) == 0) and (((x_size[3] - 1) % 8) == 0)) h = x_size[2] w = x_size[3] x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.conv2(x) x = self.bn2(x) x = self.relu(x) x = self.layer1(x) x_list = [] for i in range(self.stage2_cfg.NUM_BRANCHES): if (self.transition1[i] is not None): x_list.append(self.transition1[i](x)) else: x_list.append(x) y_list = self.stage2(x_list) x_list = [] for i in range(self.stage3_cfg.NUM_BRANCHES): if (self.transition2[i] is not None): x_list.append(self.transition2[i](y_list[(- 1)])) else: x_list.append(y_list[i]) y_list = self.stage3(x_list) x_list = [] for i in range(self.stage4_cfg.NUM_BRANCHES): if (self.transition3[i] is not None): x_list.append(self.transition3[i](y_list[(- 1)])) else: x_list.append(y_list[i]) x = self.stage4(x_list) (x0_h, x0_w) = (x[0].size(2), x[0].size(3)) x1 = F.upsample(x[1], size=(x0_h, x0_w), mode='bilinear') x2 = F.upsample(x[2], size=(x0_h, x0_w), mode='bilinear') x3 = F.upsample(x[3], size=(x0_h, x0_w), mode='bilinear') x = torch.cat([x[0], x1, x2, x3], 1) x = self.last_layer(x) x = F.interpolate(x, size=(h, w), mode='bilinear', align_corners=True) if self.training: main_loss = self.criterion(x, y) return (x.max(1)[1], main_loss, (main_loss * 0)) else: return x
Network starts from a stem of two strided 3 × 3 convolutions decreasing the resolution to 1/4. Rescale the low-resolution representations through bilinear upsampling to the high resolution, and concatenate the subsets of such representations. At end, the segmentation maps are upsampled (4 times) to the input size by bilinear upsampling for both training and testing.
mseg_semantic/model/seg_hrnet.py
forward
Shawn207/mseg-semantic
0
python
def forward(self, x: torch.Tensor, y: Optional[torch.Tensor]=None): '\n Network starts from a stem of two strided 3 × 3 convolutions\n decreasing the resolution to 1/4.\n\n Rescale the low-resolution representations through bilinear\n upsampling to the high resolution, and concatenate the subsets\n of such representations.\n\n At end, the segmentation maps are upsampled (4 times) to the\n input size by bilinear upsampling for both training and testing.\n ' x_size = x.size() assert ((((x_size[2] - 1) % 8) == 0) and (((x_size[3] - 1) % 8) == 0)) h = x_size[2] w = x_size[3] x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.conv2(x) x = self.bn2(x) x = self.relu(x) x = self.layer1(x) x_list = [] for i in range(self.stage2_cfg.NUM_BRANCHES): if (self.transition1[i] is not None): x_list.append(self.transition1[i](x)) else: x_list.append(x) y_list = self.stage2(x_list) x_list = [] for i in range(self.stage3_cfg.NUM_BRANCHES): if (self.transition2[i] is not None): x_list.append(self.transition2[i](y_list[(- 1)])) else: x_list.append(y_list[i]) y_list = self.stage3(x_list) x_list = [] for i in range(self.stage4_cfg.NUM_BRANCHES): if (self.transition3[i] is not None): x_list.append(self.transition3[i](y_list[(- 1)])) else: x_list.append(y_list[i]) x = self.stage4(x_list) (x0_h, x0_w) = (x[0].size(2), x[0].size(3)) x1 = F.upsample(x[1], size=(x0_h, x0_w), mode='bilinear') x2 = F.upsample(x[2], size=(x0_h, x0_w), mode='bilinear') x3 = F.upsample(x[3], size=(x0_h, x0_w), mode='bilinear') x = torch.cat([x[0], x1, x2, x3], 1) x = self.last_layer(x) x = F.interpolate(x, size=(h, w), mode='bilinear', align_corners=True) if self.training: main_loss = self.criterion(x, y) return (x.max(1)[1], main_loss, (main_loss * 0)) else: return x
def forward(self, x: torch.Tensor, y: Optional[torch.Tensor]=None): '\n Network starts from a stem of two strided 3 × 3 convolutions\n decreasing the resolution to 1/4.\n\n Rescale the low-resolution representations through bilinear\n upsampling to the high resolution, and concatenate the subsets\n of such representations.\n\n At end, the segmentation maps are upsampled (4 times) to the\n input size by bilinear upsampling for both training and testing.\n ' x_size = x.size() assert ((((x_size[2] - 1) % 8) == 0) and (((x_size[3] - 1) % 8) == 0)) h = x_size[2] w = x_size[3] x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.conv2(x) x = self.bn2(x) x = self.relu(x) x = self.layer1(x) x_list = [] for i in range(self.stage2_cfg.NUM_BRANCHES): if (self.transition1[i] is not None): x_list.append(self.transition1[i](x)) else: x_list.append(x) y_list = self.stage2(x_list) x_list = [] for i in range(self.stage3_cfg.NUM_BRANCHES): if (self.transition2[i] is not None): x_list.append(self.transition2[i](y_list[(- 1)])) else: x_list.append(y_list[i]) y_list = self.stage3(x_list) x_list = [] for i in range(self.stage4_cfg.NUM_BRANCHES): if (self.transition3[i] is not None): x_list.append(self.transition3[i](y_list[(- 1)])) else: x_list.append(y_list[i]) x = self.stage4(x_list) (x0_h, x0_w) = (x[0].size(2), x[0].size(3)) x1 = F.upsample(x[1], size=(x0_h, x0_w), mode='bilinear') x2 = F.upsample(x[2], size=(x0_h, x0_w), mode='bilinear') x3 = F.upsample(x[3], size=(x0_h, x0_w), mode='bilinear') x = torch.cat([x[0], x1, x2, x3], 1) x = self.last_layer(x) x = F.interpolate(x, size=(h, w), mode='bilinear', align_corners=True) if self.training: main_loss = self.criterion(x, y) return (x.max(1)[1], main_loss, (main_loss * 0)) else: return x<|docstring|>Network starts from a stem of two strided 3 × 3 convolutions decreasing the resolution to 1/4. Rescale the low-resolution representations through bilinear upsampling to the high resolution, and concatenate the subsets of such representations. At end, the segmentation maps are upsampled (4 times) to the input size by bilinear upsampling for both training and testing.<|endoftext|>
06ae731098bb7bbf757793cc559cfe20cc2070f873be30304027e83df70d0b20
def init_weights(self, load_imagenet_model: bool=False, imagenet_ckpt_fpath: str='') -> None: 'For training, we use a model pretrained on ImageNet. Irrelevant at inference.\n Args:\n load_imagenet_model:\n imagenet_ckpt_fpath: str representing path to pretrained model.\n ' logger.info('=> init weights from normal distribution') for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.normal_(m.weight, std=0.001) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) if (not load_imagenet_model): return if os.path.isfile(imagenet_ckpt_fpath): pretrained_dict = torch.load(imagenet_ckpt_fpath) logger.info('=> loading pretrained model {}'.format(imagenet_ckpt_fpath)) model_dict = self.state_dict() pretrained_dict = {k: v for (k, v) in pretrained_dict.items() if (k in model_dict.keys())} model_dict.update(pretrained_dict) self.load_state_dict(model_dict) else: logger.info('cannot find ImageNet model path, use random initialization') raise Exception('no pretrained model found at {}'.format(imagenet_ckpt_fpath))
For training, we use a model pretrained on ImageNet. Irrelevant at inference. Args: load_imagenet_model: imagenet_ckpt_fpath: str representing path to pretrained model.
mseg_semantic/model/seg_hrnet.py
init_weights
Shawn207/mseg-semantic
0
python
def init_weights(self, load_imagenet_model: bool=False, imagenet_ckpt_fpath: str=) -> None: 'For training, we use a model pretrained on ImageNet. Irrelevant at inference.\n Args:\n load_imagenet_model:\n imagenet_ckpt_fpath: str representing path to pretrained model.\n ' logger.info('=> init weights from normal distribution') for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.normal_(m.weight, std=0.001) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) if (not load_imagenet_model): return if os.path.isfile(imagenet_ckpt_fpath): pretrained_dict = torch.load(imagenet_ckpt_fpath) logger.info('=> loading pretrained model {}'.format(imagenet_ckpt_fpath)) model_dict = self.state_dict() pretrained_dict = {k: v for (k, v) in pretrained_dict.items() if (k in model_dict.keys())} model_dict.update(pretrained_dict) self.load_state_dict(model_dict) else: logger.info('cannot find ImageNet model path, use random initialization') raise Exception('no pretrained model found at {}'.format(imagenet_ckpt_fpath))
def init_weights(self, load_imagenet_model: bool=False, imagenet_ckpt_fpath: str=) -> None: 'For training, we use a model pretrained on ImageNet. Irrelevant at inference.\n Args:\n load_imagenet_model:\n imagenet_ckpt_fpath: str representing path to pretrained model.\n ' logger.info('=> init weights from normal distribution') for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.normal_(m.weight, std=0.001) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) if (not load_imagenet_model): return if os.path.isfile(imagenet_ckpt_fpath): pretrained_dict = torch.load(imagenet_ckpt_fpath) logger.info('=> loading pretrained model {}'.format(imagenet_ckpt_fpath)) model_dict = self.state_dict() pretrained_dict = {k: v for (k, v) in pretrained_dict.items() if (k in model_dict.keys())} model_dict.update(pretrained_dict) self.load_state_dict(model_dict) else: logger.info('cannot find ImageNet model path, use random initialization') raise Exception('no pretrained model found at {}'.format(imagenet_ckpt_fpath))<|docstring|>For training, we use a model pretrained on ImageNet. Irrelevant at inference. Args: load_imagenet_model: imagenet_ckpt_fpath: str representing path to pretrained model.<|endoftext|>
71d1c1388f48687b538f05a6147132312b5aa83a0401e528b29b6e9dc3f3ecde
def import_raw_data(): '\n import and minimal processing of taxonomy from excel \n ' taxonomy = pd.read_excel((os.path.abspath(os.path.join('..', 'data/raw')) + '/tagging_table.xlsx')) columnNames = taxonomy.iloc[0] taxonomy = taxonomy[1:] taxonomy.columns = columnNames print('raw data shape:', taxonomy.shape) taxonomy = taxonomy[taxonomy['PIMS #'].notna()] print('only entries with PIMS ID:', taxonomy.shape) taxonomy = taxonomy.loc[(:, taxonomy.columns.notnull())] print('only columns with entries:', taxonomy.shape) taxonomy.columns = taxonomy.columns.str.replace(' ', '_').str.lower() return taxonomy
import and minimal processing of taxonomy from excel
src/make_dataset.py
import_raw_data
OumaimaHourrane/SmallDataLongDocuments
0
python
def import_raw_data(): '\n \n ' taxonomy = pd.read_excel((os.path.abspath(os.path.join('..', 'data/raw')) + '/tagging_table.xlsx')) columnNames = taxonomy.iloc[0] taxonomy = taxonomy[1:] taxonomy.columns = columnNames print('raw data shape:', taxonomy.shape) taxonomy = taxonomy[taxonomy['PIMS #'].notna()] print('only entries with PIMS ID:', taxonomy.shape) taxonomy = taxonomy.loc[(:, taxonomy.columns.notnull())] print('only columns with entries:', taxonomy.shape) taxonomy.columns = taxonomy.columns.str.replace(' ', '_').str.lower() return taxonomy
def import_raw_data(): '\n \n ' taxonomy = pd.read_excel((os.path.abspath(os.path.join('..', 'data/raw')) + '/tagging_table.xlsx')) columnNames = taxonomy.iloc[0] taxonomy = taxonomy[1:] taxonomy.columns = columnNames print('raw data shape:', taxonomy.shape) taxonomy = taxonomy[taxonomy['PIMS #'].notna()] print('only entries with PIMS ID:', taxonomy.shape) taxonomy = taxonomy.loc[(:, taxonomy.columns.notnull())] print('only columns with entries:', taxonomy.shape) taxonomy.columns = taxonomy.columns.str.replace(' ', '_').str.lower() return taxonomy<|docstring|>import and minimal processing of taxonomy from excel<|endoftext|>
02fd9676016784462938142746917f546604f15bd5c207a93e5f261c132f7755
def import_api_data(): '\n function that imports data from PIMS+ API. \n '
function that imports data from PIMS+ API.
src/make_dataset.py
import_api_data
OumaimaHourrane/SmallDataLongDocuments
0
python
def import_api_data(): '\n \n '
def import_api_data(): '\n \n '<|docstring|>function that imports data from PIMS+ API.<|endoftext|>
f0744d80c4586ccf899452a4d16989f479e4879ed09569e9f9a1b6ec48ba0d1d
def create_subset(dataframe, column_title): '\n Takes datafram as input and column name and outputs a dataframe with two columns: project_id and column without empty fields.\n - may be appended with more meta_data than only project_id for downstream tasks.\n \n ' print('deleting all empty fields and creating subset for:', column_title) data = dataframe[dataframe[column_title].notna()] data = data[['pims_#', column_title]] print('remaining projects with non empty field', column_title, data.shape) with open((((os.path.abspath(os.path.join('..', 'data/interim')) + '/') + column_title) + '.pkl'), 'wb') as handle: pickle.dump(data, handle, protocol=pickle.HIGHEST_PROTOCOL) with open((((os.path.join('/Users/jonas/Google Drive/jupyter/ClosedDomainQA/data') + '/') + column_title) + '.pkl'), 'wb') as handle: pickle.dump(data, handle, protocol=pickle.HIGHEST_PROTOCOL) return data
Takes datafram as input and column name and outputs a dataframe with two columns: project_id and column without empty fields. - may be appended with more meta_data than only project_id for downstream tasks.
src/make_dataset.py
create_subset
OumaimaHourrane/SmallDataLongDocuments
0
python
def create_subset(dataframe, column_title): '\n Takes datafram as input and column name and outputs a dataframe with two columns: project_id and column without empty fields.\n - may be appended with more meta_data than only project_id for downstream tasks.\n \n ' print('deleting all empty fields and creating subset for:', column_title) data = dataframe[dataframe[column_title].notna()] data = data[['pims_#', column_title]] print('remaining projects with non empty field', column_title, data.shape) with open((((os.path.abspath(os.path.join('..', 'data/interim')) + '/') + column_title) + '.pkl'), 'wb') as handle: pickle.dump(data, handle, protocol=pickle.HIGHEST_PROTOCOL) with open((((os.path.join('/Users/jonas/Google Drive/jupyter/ClosedDomainQA/data') + '/') + column_title) + '.pkl'), 'wb') as handle: pickle.dump(data, handle, protocol=pickle.HIGHEST_PROTOCOL) return data
def create_subset(dataframe, column_title): '\n Takes datafram as input and column name and outputs a dataframe with two columns: project_id and column without empty fields.\n - may be appended with more meta_data than only project_id for downstream tasks.\n \n ' print('deleting all empty fields and creating subset for:', column_title) data = dataframe[dataframe[column_title].notna()] data = data[['pims_#', column_title]] print('remaining projects with non empty field', column_title, data.shape) with open((((os.path.abspath(os.path.join('..', 'data/interim')) + '/') + column_title) + '.pkl'), 'wb') as handle: pickle.dump(data, handle, protocol=pickle.HIGHEST_PROTOCOL) with open((((os.path.join('/Users/jonas/Google Drive/jupyter/ClosedDomainQA/data') + '/') + column_title) + '.pkl'), 'wb') as handle: pickle.dump(data, handle, protocol=pickle.HIGHEST_PROTOCOL) return data<|docstring|>Takes datafram as input and column name and outputs a dataframe with two columns: project_id and column without empty fields. - may be appended with more meta_data than only project_id for downstream tasks.<|endoftext|>
9440f39df58ae8113b6bda1d07b9a0c6db7d391817f5a489ad0876d6eccf0266
def create_training_texts(dataframem, compare_with_API=bool): '\n 1. Takes in whole taxonomy and outputs different training data text fields:\n i) descriptions\n ii) objecitves\n iii) outputs\n iv) outcomes\n iii)logframe (objectives + outputs + outcomes)\n iv) all (descriptoins + logframe)\n \n ' ' \n 2. if bool is set as True: Compare with downloaded logframes, descriptions and objectives from PIMS+ to see if they \n match in length and compleetness.\n - Replace empty fields with non-empty fiels if applicable.\n \n ' if (compare_with_API == True): 'compare with PIMS+ projects/logframes etc and only keep most relevant' print('Pims_plus API is considered to complete training data') if (compare_with_API == False): print('only taxonomy data is considered')
1. Takes in whole taxonomy and outputs different training data text fields: i) descriptions ii) objecitves iii) outputs iv) outcomes iii)logframe (objectives + outputs + outcomes) iv) all (descriptoins + logframe)
src/make_dataset.py
create_training_texts
OumaimaHourrane/SmallDataLongDocuments
0
python
def create_training_texts(dataframem, compare_with_API=bool): '\n 1. Takes in whole taxonomy and outputs different training data text fields:\n i) descriptions\n ii) objecitves\n iii) outputs\n iv) outcomes\n iii)logframe (objectives + outputs + outcomes)\n iv) all (descriptoins + logframe)\n \n ' ' \n 2. if bool is set as True: Compare with downloaded logframes, descriptions and objectives from PIMS+ to see if they \n match in length and compleetness.\n - Replace empty fields with non-empty fiels if applicable.\n \n ' if (compare_with_API == True): 'compare with PIMS+ projects/logframes etc and only keep most relevant' print('Pims_plus API is considered to complete training data') if (compare_with_API == False): print('only taxonomy data is considered')
def create_training_texts(dataframem, compare_with_API=bool): '\n 1. Takes in whole taxonomy and outputs different training data text fields:\n i) descriptions\n ii) objecitves\n iii) outputs\n iv) outcomes\n iii)logframe (objectives + outputs + outcomes)\n iv) all (descriptoins + logframe)\n \n ' ' \n 2. if bool is set as True: Compare with downloaded logframes, descriptions and objectives from PIMS+ to see if they \n match in length and compleetness.\n - Replace empty fields with non-empty fiels if applicable.\n \n ' if (compare_with_API == True): 'compare with PIMS+ projects/logframes etc and only keep most relevant' print('Pims_plus API is considered to complete training data') if (compare_with_API == False): print('only taxonomy data is considered')<|docstring|>1. Takes in whole taxonomy and outputs different training data text fields: i) descriptions ii) objecitves iii) outputs iv) outcomes iii)logframe (objectives + outputs + outcomes) iv) all (descriptoins + logframe)<|endoftext|>
30a4ed983f39a826010ebe8f9f1886338a01394b338ee594d5f35f1fcc16acc3
def labeling_encoding(dataframe, categories, label_powerset=bool): '\n Function that encodes the label and gives option for different classification architectures (for example label_powerset)\n ' df = pd.DataFrame(dataframe, columns=categories) dum_df = pd.get_dummies(df, columns=categories) df = df.join(dum_df) return df
Function that encodes the label and gives option for different classification architectures (for example label_powerset)
src/make_dataset.py
labeling_encoding
OumaimaHourrane/SmallDataLongDocuments
0
python
def labeling_encoding(dataframe, categories, label_powerset=bool): '\n \n ' df = pd.DataFrame(dataframe, columns=categories) dum_df = pd.get_dummies(df, columns=categories) df = df.join(dum_df) return df
def labeling_encoding(dataframe, categories, label_powerset=bool): '\n \n ' df = pd.DataFrame(dataframe, columns=categories) dum_df = pd.get_dummies(df, columns=categories) df = df.join(dum_df) return df<|docstring|>Function that encodes the label and gives option for different classification architectures (for example label_powerset)<|endoftext|>
0076d98ff8a638ad240d390edf0477c284c0aecece506335277efd95c0dd73ac
def is_external_module(self, module): '\n The modules returned by is_external_module will be clustered into one single node group.\n \n This does not affect dependency gathering for these modules currently. If these modules depend\n on other modules, these dependencies will be shown in the output graph.\n See python.depgraph2dot for modifying dependency gathering. \n ' return (module in ('csv', 'pymssql', 'datetime', 'imp', 'modulefinder'))
The modules returned by is_external_module will be clustered into one single node group. This does not affect dependency gathering for these modules currently. If these modules depend on other modules, these dependencies will be shown in the output graph. See python.depgraph2dot for modifying dependency gathering.
python/modules.py
is_external_module
btc-ag/revengtools
2
python
def is_external_module(self, module): '\n The modules returned by is_external_module will be clustered into one single node group.\n \n This does not affect dependency gathering for these modules currently. If these modules depend\n on other modules, these dependencies will be shown in the output graph.\n See python.depgraph2dot for modifying dependency gathering. \n ' return (module in ('csv', 'pymssql', 'datetime', 'imp', 'modulefinder'))
def is_external_module(self, module): '\n The modules returned by is_external_module will be clustered into one single node group.\n \n This does not affect dependency gathering for these modules currently. If these modules depend\n on other modules, these dependencies will be shown in the output graph.\n See python.depgraph2dot for modifying dependency gathering. \n ' return (module in ('csv', 'pymssql', 'datetime', 'imp', 'modulefinder'))<|docstring|>The modules returned by is_external_module will be clustered into one single node group. This does not affect dependency gathering for these modules currently. If these modules depend on other modules, these dependencies will be shown in the output graph. See python.depgraph2dot for modifying dependency gathering.<|endoftext|>
7d64ca08657b0eb740ed84bf5e17d96c926499a05f0bf30a16e72ee4a2ce88af
def emCorrectnessTest(fileName='None', resultsPath='None', verbose='False', modes="['ems']", maxFrames='20', dataTypes="['matrix', 'vertex', 'screen']", emSetup='0'): "\n Evaluate the file in multiple evaluation manager modes and compare the results.\n \n fileName: See fileName parameter in run_correctness_test.\n resultsPath: See resultsPath parameter in run_correctness_test.\n verbose: See verbose parameter in run_correctness_test.\n modes: List of modes to run the tests in. 'ems' and 'emp' are the\n only valid ones. A mode can optionally enable or disable an\n evaluator as follows:\n 'ems+deformer': Run in EM Serial mode with the deformer evalutor turned on\n 'emp-dynamics': Run in EM Parallel mode with the dynamics evalutor turned off\n 'ems+deformer-dynamics': Run in EM Serial mode with the dynamics evalutor\n turned off and the deformer evaluator turned on\n maxFrames: See maxFrames parameter in run_correctness_test.\n dataTypes: See dataTypes parameter in run_correctness_test.\n emSetup: See emSetup parameter in run_correctness_test.\n \n Returns the output of run_correctness_test().\n " pass
Evaluate the file in multiple evaluation manager modes and compare the results. fileName: See fileName parameter in run_correctness_test. resultsPath: See resultsPath parameter in run_correctness_test. verbose: See verbose parameter in run_correctness_test. modes: List of modes to run the tests in. 'ems' and 'emp' are the only valid ones. A mode can optionally enable or disable an evaluator as follows: 'ems+deformer': Run in EM Serial mode with the deformer evalutor turned on 'emp-dynamics': Run in EM Parallel mode with the dynamics evalutor turned off 'ems+deformer-dynamics': Run in EM Serial mode with the dynamics evalutor turned off and the deformer evaluator turned on maxFrames: See maxFrames parameter in run_correctness_test. dataTypes: See dataTypes parameter in run_correctness_test. emSetup: See emSetup parameter in run_correctness_test. Returns the output of run_correctness_test().
mayaSDK/maya/debug/emCorrectnessTest.py
emCorrectnessTest
FXTD-ODYSSEY/vscode-mayapy
20
python
def emCorrectnessTest(fileName='None', resultsPath='None', verbose='False', modes="['ems']", maxFrames='20', dataTypes="['matrix', 'vertex', 'screen']", emSetup='0'): "\n Evaluate the file in multiple evaluation manager modes and compare the results.\n \n fileName: See fileName parameter in run_correctness_test.\n resultsPath: See resultsPath parameter in run_correctness_test.\n verbose: See verbose parameter in run_correctness_test.\n modes: List of modes to run the tests in. 'ems' and 'emp' are the\n only valid ones. A mode can optionally enable or disable an\n evaluator as follows:\n 'ems+deformer': Run in EM Serial mode with the deformer evalutor turned on\n 'emp-dynamics': Run in EM Parallel mode with the dynamics evalutor turned off\n 'ems+deformer-dynamics': Run in EM Serial mode with the dynamics evalutor\n turned off and the deformer evaluator turned on\n maxFrames: See maxFrames parameter in run_correctness_test.\n dataTypes: See dataTypes parameter in run_correctness_test.\n emSetup: See emSetup parameter in run_correctness_test.\n \n Returns the output of run_correctness_test().\n " pass
def emCorrectnessTest(fileName='None', resultsPath='None', verbose='False', modes="['ems']", maxFrames='20', dataTypes="['matrix', 'vertex', 'screen']", emSetup='0'): "\n Evaluate the file in multiple evaluation manager modes and compare the results.\n \n fileName: See fileName parameter in run_correctness_test.\n resultsPath: See resultsPath parameter in run_correctness_test.\n verbose: See verbose parameter in run_correctness_test.\n modes: List of modes to run the tests in. 'ems' and 'emp' are the\n only valid ones. A mode can optionally enable or disable an\n evaluator as follows:\n 'ems+deformer': Run in EM Serial mode with the deformer evalutor turned on\n 'emp-dynamics': Run in EM Parallel mode with the dynamics evalutor turned off\n 'ems+deformer-dynamics': Run in EM Serial mode with the dynamics evalutor\n turned off and the deformer evaluator turned on\n maxFrames: See maxFrames parameter in run_correctness_test.\n dataTypes: See dataTypes parameter in run_correctness_test.\n emSetup: See emSetup parameter in run_correctness_test.\n \n Returns the output of run_correctness_test().\n " pass<|docstring|>Evaluate the file in multiple evaluation manager modes and compare the results. fileName: See fileName parameter in run_correctness_test. resultsPath: See resultsPath parameter in run_correctness_test. verbose: See verbose parameter in run_correctness_test. modes: List of modes to run the tests in. 'ems' and 'emp' are the only valid ones. A mode can optionally enable or disable an evaluator as follows: 'ems+deformer': Run in EM Serial mode with the deformer evalutor turned on 'emp-dynamics': Run in EM Parallel mode with the dynamics evalutor turned off 'ems+deformer-dynamics': Run in EM Serial mode with the dynamics evalutor turned off and the deformer evaluator turned on maxFrames: See maxFrames parameter in run_correctness_test. dataTypes: See dataTypes parameter in run_correctness_test. emSetup: See emSetup parameter in run_correctness_test. Returns the output of run_correctness_test().<|endoftext|>
ae0561c14f46828720cb645afadf30e505f7edceca25ae2f2e3b0d122ac2f84c
def download_and_convert_dicoms(bucket='lung-cancer-ct-scans', folder='SampleImages', local_folder='./data'): 'Downloads all the dicom files in an AWS S3 bucket and saves them locally as a csv file' s3_keys = list_files_on_s3(bucket, folder_prefix=folder) MyCounter = 1 for s3_key in s3_keys: (_, _, filename) = split_s3_key(s3_key) download_ct_image_from_s3(s3_key, bucket=bucket) ct_slice = dicom.read_file('./temp.dcm').pixel_array save_location = (('./data/' + filename) + '.txt') np.savetxt(save_location, ct_slice) print('Current Image:', MyCounter) MyCounter += 1 if (MyCounter > 1000): exit()
Downloads all the dicom files in an AWS S3 bucket and saves them locally as a csv file
convert_dicoms_to_ndarrays.py
download_and_convert_dicoms
SpiroGanas/Lung-Cancer-Machine-Learning
1
python
def download_and_convert_dicoms(bucket='lung-cancer-ct-scans', folder='SampleImages', local_folder='./data'): s3_keys = list_files_on_s3(bucket, folder_prefix=folder) MyCounter = 1 for s3_key in s3_keys: (_, _, filename) = split_s3_key(s3_key) download_ct_image_from_s3(s3_key, bucket=bucket) ct_slice = dicom.read_file('./temp.dcm').pixel_array save_location = (('./data/' + filename) + '.txt') np.savetxt(save_location, ct_slice) print('Current Image:', MyCounter) MyCounter += 1 if (MyCounter > 1000): exit()
def download_and_convert_dicoms(bucket='lung-cancer-ct-scans', folder='SampleImages', local_folder='./data'): s3_keys = list_files_on_s3(bucket, folder_prefix=folder) MyCounter = 1 for s3_key in s3_keys: (_, _, filename) = split_s3_key(s3_key) download_ct_image_from_s3(s3_key, bucket=bucket) ct_slice = dicom.read_file('./temp.dcm').pixel_array save_location = (('./data/' + filename) + '.txt') np.savetxt(save_location, ct_slice) print('Current Image:', MyCounter) MyCounter += 1 if (MyCounter > 1000): exit()<|docstring|>Downloads all the dicom files in an AWS S3 bucket and saves them locally as a csv file<|endoftext|>
172787b930dae0da81ee91231c75966a741b320a50a6c92244de1ac1b137727f
@property def specs_url(self): '\n The Swagger specifications absolute url (ie. `swagger.json`)\n\n :rtype: str\n ' return url_for(self.endpoint('specs'), _external=False)
The Swagger specifications absolute url (ie. `swagger.json`) :rtype: str
sources/.history/nyx_rest_api_plus_20191118164118.py
specs_url
CofelyGTC/nyx_rest
1
python
@property def specs_url(self): '\n The Swagger specifications absolute url (ie. `swagger.json`)\n\n :rtype: str\n ' return url_for(self.endpoint('specs'), _external=False)
@property def specs_url(self): '\n The Swagger specifications absolute url (ie. `swagger.json`)\n\n :rtype: str\n ' return url_for(self.endpoint('specs'), _external=False)<|docstring|>The Swagger specifications absolute url (ie. `swagger.json`) :rtype: str<|endoftext|>
83f3f7e92cad56207a9391b18b3457cf89e2f2f2b90595f2228e69d3040e0551
def __init__(self, resolver_context, file_system, path_spec, is_root=False, is_virtual=False): 'Initializes a file entry.\n\n Args:\n resolver_context (Context): resolver context.\n file_system (FileSystem): file system.\n path_spec (PathSpec): path specification.\n is_root (Optional[bool]): True if the file entry is the root file entry\n of the corresponding file system.\n is_virtual (Optional[bool]): True if the file entry is a virtual file\n entry emulated by the corresponding file system.\n\n Raises:\n BackEndError: when the FVDE volume is missing.\n ' fvde_volume = file_system.GetFVDEVolume() if (fvde_volume is None): raise errors.BackEndError('Missing FVDE volume.') super(FVDEFileEntry, self).__init__(resolver_context, file_system, path_spec, is_root=is_root, is_virtual=is_virtual) self._fvde_volume = fvde_volume self.entry_type = definitions.FILE_ENTRY_TYPE_FILE
Initializes a file entry. Args: resolver_context (Context): resolver context. file_system (FileSystem): file system. path_spec (PathSpec): path specification. is_root (Optional[bool]): True if the file entry is the root file entry of the corresponding file system. is_virtual (Optional[bool]): True if the file entry is a virtual file entry emulated by the corresponding file system. Raises: BackEndError: when the FVDE volume is missing.
dfvfs/vfs/fvde_file_entry.py
__init__
Acidburn0zzz/dfvfs
1
python
def __init__(self, resolver_context, file_system, path_spec, is_root=False, is_virtual=False): 'Initializes a file entry.\n\n Args:\n resolver_context (Context): resolver context.\n file_system (FileSystem): file system.\n path_spec (PathSpec): path specification.\n is_root (Optional[bool]): True if the file entry is the root file entry\n of the corresponding file system.\n is_virtual (Optional[bool]): True if the file entry is a virtual file\n entry emulated by the corresponding file system.\n\n Raises:\n BackEndError: when the FVDE volume is missing.\n ' fvde_volume = file_system.GetFVDEVolume() if (fvde_volume is None): raise errors.BackEndError('Missing FVDE volume.') super(FVDEFileEntry, self).__init__(resolver_context, file_system, path_spec, is_root=is_root, is_virtual=is_virtual) self._fvde_volume = fvde_volume self.entry_type = definitions.FILE_ENTRY_TYPE_FILE
def __init__(self, resolver_context, file_system, path_spec, is_root=False, is_virtual=False): 'Initializes a file entry.\n\n Args:\n resolver_context (Context): resolver context.\n file_system (FileSystem): file system.\n path_spec (PathSpec): path specification.\n is_root (Optional[bool]): True if the file entry is the root file entry\n of the corresponding file system.\n is_virtual (Optional[bool]): True if the file entry is a virtual file\n entry emulated by the corresponding file system.\n\n Raises:\n BackEndError: when the FVDE volume is missing.\n ' fvde_volume = file_system.GetFVDEVolume() if (fvde_volume is None): raise errors.BackEndError('Missing FVDE volume.') super(FVDEFileEntry, self).__init__(resolver_context, file_system, path_spec, is_root=is_root, is_virtual=is_virtual) self._fvde_volume = fvde_volume self.entry_type = definitions.FILE_ENTRY_TYPE_FILE<|docstring|>Initializes a file entry. Args: resolver_context (Context): resolver context. file_system (FileSystem): file system. path_spec (PathSpec): path specification. is_root (Optional[bool]): True if the file entry is the root file entry of the corresponding file system. is_virtual (Optional[bool]): True if the file entry is a virtual file entry emulated by the corresponding file system. Raises: BackEndError: when the FVDE volume is missing.<|endoftext|>
f33a0d9b8f7ad8845bcc51624e8e47c123771afb08ce5da771a6af19fbf68a2c
def _GetStat(self): 'Retrieves information about the file entry.\n\n Returns:\n VFSStat: a stat object.\n ' stat_object = super(FVDEFileEntry, self)._GetStat() stat_object.size = self._fvde_volume.get_size() return stat_object
Retrieves information about the file entry. Returns: VFSStat: a stat object.
dfvfs/vfs/fvde_file_entry.py
_GetStat
Acidburn0zzz/dfvfs
1
python
def _GetStat(self): 'Retrieves information about the file entry.\n\n Returns:\n VFSStat: a stat object.\n ' stat_object = super(FVDEFileEntry, self)._GetStat() stat_object.size = self._fvde_volume.get_size() return stat_object
def _GetStat(self): 'Retrieves information about the file entry.\n\n Returns:\n VFSStat: a stat object.\n ' stat_object = super(FVDEFileEntry, self)._GetStat() stat_object.size = self._fvde_volume.get_size() return stat_object<|docstring|>Retrieves information about the file entry. Returns: VFSStat: a stat object.<|endoftext|>
1437b02ac3bf4ff2fc74a3dba971537fea1495f8a588840bf865306ce8782168
def serialize_roku_object_for_selection(roku: Roku) -> dict: '\n Serailizes Roku into a usable dict to prompt.\n :param roku: Roku device\n :return: choice dict for prompt\n ' return {'name': roku.friendly_device_name, 'value': roku}
Serailizes Roku into a usable dict to prompt. :param roku: Roku device :return: choice dict for prompt
pyku/utils.py
serialize_roku_object_for_selection
CCecilia/PyKu
0
python
def serialize_roku_object_for_selection(roku: Roku) -> dict: '\n Serailizes Roku into a usable dict to prompt.\n :param roku: Roku device\n :return: choice dict for prompt\n ' return {'name': roku.friendly_device_name, 'value': roku}
def serialize_roku_object_for_selection(roku: Roku) -> dict: '\n Serailizes Roku into a usable dict to prompt.\n :param roku: Roku device\n :return: choice dict for prompt\n ' return {'name': roku.friendly_device_name, 'value': roku}<|docstring|>Serailizes Roku into a usable dict to prompt. :param roku: Roku device :return: choice dict for prompt<|endoftext|>
05aab2580e346932c87bf57306db1070b48fbad75bd7d8a3615cd7ae886c71d0
def merge_roku_config_values_into_dict(config_rokus: list) -> dict: '\n Merges the list dicts and values from config into one dict for ease of access\n :param config_rokus: list of roku cofig value dict\n :return: a single dict of config values\n ' return {key: value for config in config_rokus for (key, value) in config.items()}
Merges the list dicts and values from config into one dict for ease of access :param config_rokus: list of roku cofig value dict :return: a single dict of config values
pyku/utils.py
merge_roku_config_values_into_dict
CCecilia/PyKu
0
python
def merge_roku_config_values_into_dict(config_rokus: list) -> dict: '\n Merges the list dicts and values from config into one dict for ease of access\n :param config_rokus: list of roku cofig value dict\n :return: a single dict of config values\n ' return {key: value for config in config_rokus for (key, value) in config.items()}
def merge_roku_config_values_into_dict(config_rokus: list) -> dict: '\n Merges the list dicts and values from config into one dict for ease of access\n :param config_rokus: list of roku cofig value dict\n :return: a single dict of config values\n ' return {key: value for config in config_rokus for (key, value) in config.items()}<|docstring|>Merges the list dicts and values from config into one dict for ease of access :param config_rokus: list of roku cofig value dict :return: a single dict of config values<|endoftext|>
036498adfb39c28a0581d6b9fd04af2034fdf56a5ed7cf95a25ba0a650eb5756
def check_if_roku_exists_in_config(roku: Roku, channel: Channel) -> Union[(None, dict)]: "\n Checks if a Roku's ip address exists in the config and returns amerged version of it if True else None\n :param roku: Roku device\n :param channel: Channel\n :return:\n " config_rokus: Union[(list, None)] = channel.channel_config.rokus if ((config_rokus is not None) and (len(config_rokus) > 0)): for index in range(len(config_rokus)): ip_address: Union[(str, None)] = config_rokus[index][0].get('ip_address', None) if ((ip_address is not None) and (roku.location.find(ip_address) != (- 1))): return merge_roku_config_values_into_dict(config_rokus[index]) return None
Checks if a Roku's ip address exists in the config and returns amerged version of it if True else None :param roku: Roku device :param channel: Channel :return:
pyku/utils.py
check_if_roku_exists_in_config
CCecilia/PyKu
0
python
def check_if_roku_exists_in_config(roku: Roku, channel: Channel) -> Union[(None, dict)]: "\n Checks if a Roku's ip address exists in the config and returns amerged version of it if True else None\n :param roku: Roku device\n :param channel: Channel\n :return:\n " config_rokus: Union[(list, None)] = channel.channel_config.rokus if ((config_rokus is not None) and (len(config_rokus) > 0)): for index in range(len(config_rokus)): ip_address: Union[(str, None)] = config_rokus[index][0].get('ip_address', None) if ((ip_address is not None) and (roku.location.find(ip_address) != (- 1))): return merge_roku_config_values_into_dict(config_rokus[index]) return None
def check_if_roku_exists_in_config(roku: Roku, channel: Channel) -> Union[(None, dict)]: "\n Checks if a Roku's ip address exists in the config and returns amerged version of it if True else None\n :param roku: Roku device\n :param channel: Channel\n :return:\n " config_rokus: Union[(list, None)] = channel.channel_config.rokus if ((config_rokus is not None) and (len(config_rokus) > 0)): for index in range(len(config_rokus)): ip_address: Union[(str, None)] = config_rokus[index][0].get('ip_address', None) if ((ip_address is not None) and (roku.location.find(ip_address) != (- 1))): return merge_roku_config_values_into_dict(config_rokus[index]) return None<|docstring|>Checks if a Roku's ip address exists in the config and returns amerged version of it if True else None :param roku: Roku device :param channel: Channel :return:<|endoftext|>
0e4b4ed6abb9a2f2f7ae5733ada09c8617b7c08f4c46cb7b1b9718d861b49341
def run_device_discovery(channel: Channel) -> list: '\n Discovers devices on LAN and cross references config for password or prompts user for it\n :param channel: Channel\n :return: list of selected devices\n ' click.echo('discovering devices') scanner: Scanner = Scanner() scanner.discover() selected_devices: list = [] rokus: list = [] for device in scanner.discovered_devices: roku_location: str = device.get('LOCATION') roku: Roku = Roku(location=roku_location, discovery_data=device) roku.fetch_data() rokus.append(roku) if (len(rokus) > 0): choices: list = [serialize_roku_object_for_selection(roku) for roku in rokus if roku.developer_enabled] device_selection_questions: list = [{'type': 'checkbox', 'message': 'Select Device(s)', 'name': 'selected_devices', 'choices': choices, 'validate': (lambda answer: ('You must choose at least one device.' if (len(answer) == 0) else True))}] selected_rokus: dict = prompt(device_selection_questions) selected_devices.append(selected_rokus.get('selected_devices', [])) if (len(selected_devices) > 0): for selected in selected_devices: config_check: Union[(None, dict)] = check_if_roku_exists_in_config(selected, channel) if (config_check is not None): selected.password = config_check.get('password', None) selected.selected = True config_username: Union[(str, None)] = config_check.get('username', None) if (config_username is not None): selected.user_name = config_username else: password_prompt: str = click.prompt(f'password for {selected.location}', prompt_suffix='? ', type=str) if (password_prompt != ''): selected.password = password_prompt selected.selected = True else: selected_devices.remove(selected) click.echo(f'unable to use {selected.friendly_model_name} @ {selected.location}') return selected_devices
Discovers devices on LAN and cross references config for password or prompts user for it :param channel: Channel :return: list of selected devices
pyku/utils.py
run_device_discovery
CCecilia/PyKu
0
python
def run_device_discovery(channel: Channel) -> list: '\n Discovers devices on LAN and cross references config for password or prompts user for it\n :param channel: Channel\n :return: list of selected devices\n ' click.echo('discovering devices') scanner: Scanner = Scanner() scanner.discover() selected_devices: list = [] rokus: list = [] for device in scanner.discovered_devices: roku_location: str = device.get('LOCATION') roku: Roku = Roku(location=roku_location, discovery_data=device) roku.fetch_data() rokus.append(roku) if (len(rokus) > 0): choices: list = [serialize_roku_object_for_selection(roku) for roku in rokus if roku.developer_enabled] device_selection_questions: list = [{'type': 'checkbox', 'message': 'Select Device(s)', 'name': 'selected_devices', 'choices': choices, 'validate': (lambda answer: ('You must choose at least one device.' if (len(answer) == 0) else True))}] selected_rokus: dict = prompt(device_selection_questions) selected_devices.append(selected_rokus.get('selected_devices', [])) if (len(selected_devices) > 0): for selected in selected_devices: config_check: Union[(None, dict)] = check_if_roku_exists_in_config(selected, channel) if (config_check is not None): selected.password = config_check.get('password', None) selected.selected = True config_username: Union[(str, None)] = config_check.get('username', None) if (config_username is not None): selected.user_name = config_username else: password_prompt: str = click.prompt(f'password for {selected.location}', prompt_suffix='? ', type=str) if (password_prompt != ): selected.password = password_prompt selected.selected = True else: selected_devices.remove(selected) click.echo(f'unable to use {selected.friendly_model_name} @ {selected.location}') return selected_devices
def run_device_discovery(channel: Channel) -> list: '\n Discovers devices on LAN and cross references config for password or prompts user for it\n :param channel: Channel\n :return: list of selected devices\n ' click.echo('discovering devices') scanner: Scanner = Scanner() scanner.discover() selected_devices: list = [] rokus: list = [] for device in scanner.discovered_devices: roku_location: str = device.get('LOCATION') roku: Roku = Roku(location=roku_location, discovery_data=device) roku.fetch_data() rokus.append(roku) if (len(rokus) > 0): choices: list = [serialize_roku_object_for_selection(roku) for roku in rokus if roku.developer_enabled] device_selection_questions: list = [{'type': 'checkbox', 'message': 'Select Device(s)', 'name': 'selected_devices', 'choices': choices, 'validate': (lambda answer: ('You must choose at least one device.' if (len(answer) == 0) else True))}] selected_rokus: dict = prompt(device_selection_questions) selected_devices.append(selected_rokus.get('selected_devices', [])) if (len(selected_devices) > 0): for selected in selected_devices: config_check: Union[(None, dict)] = check_if_roku_exists_in_config(selected, channel) if (config_check is not None): selected.password = config_check.get('password', None) selected.selected = True config_username: Union[(str, None)] = config_check.get('username', None) if (config_username is not None): selected.user_name = config_username else: password_prompt: str = click.prompt(f'password for {selected.location}', prompt_suffix='? ', type=str) if (password_prompt != ): selected.password = password_prompt selected.selected = True else: selected_devices.remove(selected) click.echo(f'unable to use {selected.friendly_model_name} @ {selected.location}') return selected_devices<|docstring|>Discovers devices on LAN and cross references config for password or prompts user for it :param channel: Channel :return: list of selected devices<|endoftext|>
a9255a71891c3edcc374e2b7c877b432eacffc93103732917db9d85e7a2b88c7
def get_selected_from_config(channel: Channel): '\n Reads config for devices and creates Roku objects\n :param channel: Channel\n :return: list of selected devices\n ' click.echo('reading config for rokus') selected_devices: list = [] config_rokus: list = channel.channel_config.rokus if (not len(config_rokus)): click.echo('cannot skip device discovery without rokus designated in config') exit() for roku_config in config_rokus: click.echo(f"found config for {roku_config.get('ip_address', '')}") roku: Roku = Roku(location=f"http://{roku_config.get('ip_address', '')}:8060/", discovery_data={'WAKEUP': '', 'device-group.roku.com': '', 'LOCATION': f"http://{roku_config.get('ip_address', '')}:8060/", 'Server': 'Roku/9.3.0 UPnP/1.0 Roku/9.3.0', 'Ext': '', 'USN': '', 'ST': 'roku:ecp', 'Cache-Control': 'max-age=3600'}) roku.fetch_data() roku.selected = True roku.password = roku_config.get('password', '') config_username: Union[(str, None)] = roku_config.get('username', None) if (config_username is not None): roku.user_name = config_username selected_devices.append(roku) return selected_devices
Reads config for devices and creates Roku objects :param channel: Channel :return: list of selected devices
pyku/utils.py
get_selected_from_config
CCecilia/PyKu
0
python
def get_selected_from_config(channel: Channel): '\n Reads config for devices and creates Roku objects\n :param channel: Channel\n :return: list of selected devices\n ' click.echo('reading config for rokus') selected_devices: list = [] config_rokus: list = channel.channel_config.rokus if (not len(config_rokus)): click.echo('cannot skip device discovery without rokus designated in config') exit() for roku_config in config_rokus: click.echo(f"found config for {roku_config.get('ip_address', )}") roku: Roku = Roku(location=f"http://{roku_config.get('ip_address', )}:8060/", discovery_data={'WAKEUP': , 'device-group.roku.com': , 'LOCATION': f"http://{roku_config.get('ip_address', )}:8060/", 'Server': 'Roku/9.3.0 UPnP/1.0 Roku/9.3.0', 'Ext': , 'USN': , 'ST': 'roku:ecp', 'Cache-Control': 'max-age=3600'}) roku.fetch_data() roku.selected = True roku.password = roku_config.get('password', ) config_username: Union[(str, None)] = roku_config.get('username', None) if (config_username is not None): roku.user_name = config_username selected_devices.append(roku) return selected_devices
def get_selected_from_config(channel: Channel): '\n Reads config for devices and creates Roku objects\n :param channel: Channel\n :return: list of selected devices\n ' click.echo('reading config for rokus') selected_devices: list = [] config_rokus: list = channel.channel_config.rokus if (not len(config_rokus)): click.echo('cannot skip device discovery without rokus designated in config') exit() for roku_config in config_rokus: click.echo(f"found config for {roku_config.get('ip_address', )}") roku: Roku = Roku(location=f"http://{roku_config.get('ip_address', )}:8060/", discovery_data={'WAKEUP': , 'device-group.roku.com': , 'LOCATION': f"http://{roku_config.get('ip_address', )}:8060/", 'Server': 'Roku/9.3.0 UPnP/1.0 Roku/9.3.0', 'Ext': , 'USN': , 'ST': 'roku:ecp', 'Cache-Control': 'max-age=3600'}) roku.fetch_data() roku.selected = True roku.password = roku_config.get('password', ) config_username: Union[(str, None)] = roku_config.get('username', None) if (config_username is not None): roku.user_name = config_username selected_devices.append(roku) return selected_devices<|docstring|>Reads config for devices and creates Roku objects :param channel: Channel :return: list of selected devices<|endoftext|>
ffcdb3ed950a4b452e496293eaefcf31271bf23099c537475808479e33f5f9c1
def _validate_single_bson_type(ctxt, idl_type, syntax_type): 'Validate bson serialization type is correct for a type.' bson_type = idl_type.bson_serialization_type[0] if (bson_type == 'any'): return True if (not bson.is_valid_bson_type(bson_type)): ctxt.add_bad_bson_type_error(idl_type, syntax_type, idl_type.name, bson_type) return False if (bson_type == 'bindata'): subtype = idl_type.bindata_subtype if (subtype is None): subtype = '<unknown>' if (not bson.is_valid_bindata_subtype(subtype)): ctxt.add_bad_bson_bindata_subtype_value_error(idl_type, syntax_type, idl_type.name, subtype) elif (idl_type.bindata_subtype is not None): ctxt.add_bad_bson_bindata_subtype_error(idl_type, syntax_type, idl_type.name, bson_type) return True
Validate bson serialization type is correct for a type.
buildscripts/idl/idl/binder.py
_validate_single_bson_type
sgweon/mongo
0
python
def _validate_single_bson_type(ctxt, idl_type, syntax_type): bson_type = idl_type.bson_serialization_type[0] if (bson_type == 'any'): return True if (not bson.is_valid_bson_type(bson_type)): ctxt.add_bad_bson_type_error(idl_type, syntax_type, idl_type.name, bson_type) return False if (bson_type == 'bindata'): subtype = idl_type.bindata_subtype if (subtype is None): subtype = '<unknown>' if (not bson.is_valid_bindata_subtype(subtype)): ctxt.add_bad_bson_bindata_subtype_value_error(idl_type, syntax_type, idl_type.name, subtype) elif (idl_type.bindata_subtype is not None): ctxt.add_bad_bson_bindata_subtype_error(idl_type, syntax_type, idl_type.name, bson_type) return True
def _validate_single_bson_type(ctxt, idl_type, syntax_type): bson_type = idl_type.bson_serialization_type[0] if (bson_type == 'any'): return True if (not bson.is_valid_bson_type(bson_type)): ctxt.add_bad_bson_type_error(idl_type, syntax_type, idl_type.name, bson_type) return False if (bson_type == 'bindata'): subtype = idl_type.bindata_subtype if (subtype is None): subtype = '<unknown>' if (not bson.is_valid_bindata_subtype(subtype)): ctxt.add_bad_bson_bindata_subtype_value_error(idl_type, syntax_type, idl_type.name, subtype) elif (idl_type.bindata_subtype is not None): ctxt.add_bad_bson_bindata_subtype_error(idl_type, syntax_type, idl_type.name, bson_type) return True<|docstring|>Validate bson serialization type is correct for a type.<|endoftext|>
0e93d153637fb12595d874cb95776b539fb7b99418179c6ac2a6618e06fdc9f7
def _validate_bson_types_list(ctxt, idl_type, syntax_type): 'Validate bson serialization type(s) is correct for a type.' bson_types = idl_type.bson_serialization_type if (len(bson_types) == 1): return _validate_single_bson_type(ctxt, idl_type, syntax_type) for bson_type in bson_types: if (bson_type == 'any'): ctxt.add_bad_any_type_use_error(idl_type, syntax_type, idl_type.name) return False if (not bson.is_valid_bson_type(bson_type)): ctxt.add_bad_bson_type_error(idl_type, syntax_type, idl_type.name, bson_type) return False if (bson_type == 'bindata'): ctxt.add_bad_bson_type_error(idl_type, syntax_type, idl_type.name, bson_type) return False if (not bson.is_scalar_bson_type(bson_type)): ctxt.add_bad_bson_scalar_type_error(idl_type, syntax_type, idl_type.name, bson_type) return False return True
Validate bson serialization type(s) is correct for a type.
buildscripts/idl/idl/binder.py
_validate_bson_types_list
sgweon/mongo
0
python
def _validate_bson_types_list(ctxt, idl_type, syntax_type): bson_types = idl_type.bson_serialization_type if (len(bson_types) == 1): return _validate_single_bson_type(ctxt, idl_type, syntax_type) for bson_type in bson_types: if (bson_type == 'any'): ctxt.add_bad_any_type_use_error(idl_type, syntax_type, idl_type.name) return False if (not bson.is_valid_bson_type(bson_type)): ctxt.add_bad_bson_type_error(idl_type, syntax_type, idl_type.name, bson_type) return False if (bson_type == 'bindata'): ctxt.add_bad_bson_type_error(idl_type, syntax_type, idl_type.name, bson_type) return False if (not bson.is_scalar_bson_type(bson_type)): ctxt.add_bad_bson_scalar_type_error(idl_type, syntax_type, idl_type.name, bson_type) return False return True
def _validate_bson_types_list(ctxt, idl_type, syntax_type): bson_types = idl_type.bson_serialization_type if (len(bson_types) == 1): return _validate_single_bson_type(ctxt, idl_type, syntax_type) for bson_type in bson_types: if (bson_type == 'any'): ctxt.add_bad_any_type_use_error(idl_type, syntax_type, idl_type.name) return False if (not bson.is_valid_bson_type(bson_type)): ctxt.add_bad_bson_type_error(idl_type, syntax_type, idl_type.name, bson_type) return False if (bson_type == 'bindata'): ctxt.add_bad_bson_type_error(idl_type, syntax_type, idl_type.name, bson_type) return False if (not bson.is_scalar_bson_type(bson_type)): ctxt.add_bad_bson_scalar_type_error(idl_type, syntax_type, idl_type.name, bson_type) return False return True<|docstring|>Validate bson serialization type(s) is correct for a type.<|endoftext|>
a09d1166045eb9d4654359c0c536b59d1a9955a4606815bf610cac6d0042a9d5
def _validate_type(ctxt, idl_type): 'Validate each type is correct.' if idl_type.name.startswith('array<'): ctxt.add_array_not_valid_error(idl_type, 'type', idl_type.name) _validate_type_properties(ctxt, idl_type, 'type')
Validate each type is correct.
buildscripts/idl/idl/binder.py
_validate_type
sgweon/mongo
0
python
def _validate_type(ctxt, idl_type): if idl_type.name.startswith('array<'): ctxt.add_array_not_valid_error(idl_type, 'type', idl_type.name) _validate_type_properties(ctxt, idl_type, 'type')
def _validate_type(ctxt, idl_type): if idl_type.name.startswith('array<'): ctxt.add_array_not_valid_error(idl_type, 'type', idl_type.name) _validate_type_properties(ctxt, idl_type, 'type')<|docstring|>Validate each type is correct.<|endoftext|>
e2cd9e0f92f326ddf3acb66b27728de4628ff328d468c1f043d28dd59945c7d0
def _validate_cpp_type(ctxt, idl_type, syntax_type): 'Validate the cpp_type is correct.' if ('StringData' in idl_type.cpp_type): ctxt.add_no_string_data_error(idl_type, syntax_type, idl_type.name) if (idl_type.cpp_type in ['char', 'wchar_t', 'char16_t', 'char32_t', 'float']): ctxt.add_bad_cpp_numeric_type_use_error(idl_type, syntax_type, idl_type.name, idl_type.cpp_type) for numeric_word in ['signed', 'unsigned', 'int', 'long', 'short']: if re.search(('\\b%s\\b' % numeric_word), idl_type.cpp_type): ctxt.add_bad_cpp_numeric_type_use_error(idl_type, syntax_type, idl_type.name, idl_type.cpp_type) return if (idl_type.cpp_type in ['std::int32_t', 'std::int64_t', 'std::uint32_t', 'std::uint64_t']): return for std_numeric_type in ['int8_t', 'int16_t', 'int32_t', 'int64_t', 'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t']: if (std_numeric_type in idl_type.cpp_type): ctxt.add_bad_cpp_numeric_type_use_error(idl_type, syntax_type, idl_type.name, idl_type.cpp_type) return
Validate the cpp_type is correct.
buildscripts/idl/idl/binder.py
_validate_cpp_type
sgweon/mongo
0
python
def _validate_cpp_type(ctxt, idl_type, syntax_type): if ('StringData' in idl_type.cpp_type): ctxt.add_no_string_data_error(idl_type, syntax_type, idl_type.name) if (idl_type.cpp_type in ['char', 'wchar_t', 'char16_t', 'char32_t', 'float']): ctxt.add_bad_cpp_numeric_type_use_error(idl_type, syntax_type, idl_type.name, idl_type.cpp_type) for numeric_word in ['signed', 'unsigned', 'int', 'long', 'short']: if re.search(('\\b%s\\b' % numeric_word), idl_type.cpp_type): ctxt.add_bad_cpp_numeric_type_use_error(idl_type, syntax_type, idl_type.name, idl_type.cpp_type) return if (idl_type.cpp_type in ['std::int32_t', 'std::int64_t', 'std::uint32_t', 'std::uint64_t']): return for std_numeric_type in ['int8_t', 'int16_t', 'int32_t', 'int64_t', 'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t']: if (std_numeric_type in idl_type.cpp_type): ctxt.add_bad_cpp_numeric_type_use_error(idl_type, syntax_type, idl_type.name, idl_type.cpp_type) return
def _validate_cpp_type(ctxt, idl_type, syntax_type): if ('StringData' in idl_type.cpp_type): ctxt.add_no_string_data_error(idl_type, syntax_type, idl_type.name) if (idl_type.cpp_type in ['char', 'wchar_t', 'char16_t', 'char32_t', 'float']): ctxt.add_bad_cpp_numeric_type_use_error(idl_type, syntax_type, idl_type.name, idl_type.cpp_type) for numeric_word in ['signed', 'unsigned', 'int', 'long', 'short']: if re.search(('\\b%s\\b' % numeric_word), idl_type.cpp_type): ctxt.add_bad_cpp_numeric_type_use_error(idl_type, syntax_type, idl_type.name, idl_type.cpp_type) return if (idl_type.cpp_type in ['std::int32_t', 'std::int64_t', 'std::uint32_t', 'std::uint64_t']): return for std_numeric_type in ['int8_t', 'int16_t', 'int32_t', 'int64_t', 'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t']: if (std_numeric_type in idl_type.cpp_type): ctxt.add_bad_cpp_numeric_type_use_error(idl_type, syntax_type, idl_type.name, idl_type.cpp_type) return<|docstring|>Validate the cpp_type is correct.<|endoftext|>
95d1fb832a5e8ad2a9fbc89e9492344cf7d6e9c51dfdf14535cc82a72fe4f6af
def _validate_type_properties(ctxt, idl_type, syntax_type): 'Validate each type or field is correct.' if (not _validate_bson_types_list(ctxt, idl_type, syntax_type)): return if (len(idl_type.bson_serialization_type) == 1): bson_type = idl_type.bson_serialization_type[0] if (bson_type == 'any'): if (idl_type.deserializer is None): ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name, 'deserializer') elif (bson_type == 'string'): if (idl_type.deserializer is None): ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name, 'deserializer') elif (not (bson_type in ['object'])): if (idl_type.deserializer is None): ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name, 'deserializer') if ((idl_type.deserializer is not None) and ('BSONElement' not in idl_type.deserializer)): ctxt.add_not_custom_scalar_serialization_not_supported_error(idl_type, syntax_type, idl_type.name, bson_type) if (idl_type.serializer is not None): ctxt.add_not_custom_scalar_serialization_not_supported_error(idl_type, syntax_type, idl_type.name, bson_type) elif (idl_type.deserializer is None): ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name, 'deserializer') _validate_cpp_type(ctxt, idl_type, syntax_type)
Validate each type or field is correct.
buildscripts/idl/idl/binder.py
_validate_type_properties
sgweon/mongo
0
python
def _validate_type_properties(ctxt, idl_type, syntax_type): if (not _validate_bson_types_list(ctxt, idl_type, syntax_type)): return if (len(idl_type.bson_serialization_type) == 1): bson_type = idl_type.bson_serialization_type[0] if (bson_type == 'any'): if (idl_type.deserializer is None): ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name, 'deserializer') elif (bson_type == 'string'): if (idl_type.deserializer is None): ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name, 'deserializer') elif (not (bson_type in ['object'])): if (idl_type.deserializer is None): ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name, 'deserializer') if ((idl_type.deserializer is not None) and ('BSONElement' not in idl_type.deserializer)): ctxt.add_not_custom_scalar_serialization_not_supported_error(idl_type, syntax_type, idl_type.name, bson_type) if (idl_type.serializer is not None): ctxt.add_not_custom_scalar_serialization_not_supported_error(idl_type, syntax_type, idl_type.name, bson_type) elif (idl_type.deserializer is None): ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name, 'deserializer') _validate_cpp_type(ctxt, idl_type, syntax_type)
def _validate_type_properties(ctxt, idl_type, syntax_type): if (not _validate_bson_types_list(ctxt, idl_type, syntax_type)): return if (len(idl_type.bson_serialization_type) == 1): bson_type = idl_type.bson_serialization_type[0] if (bson_type == 'any'): if (idl_type.deserializer is None): ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name, 'deserializer') elif (bson_type == 'string'): if (idl_type.deserializer is None): ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name, 'deserializer') elif (not (bson_type in ['object'])): if (idl_type.deserializer is None): ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name, 'deserializer') if ((idl_type.deserializer is not None) and ('BSONElement' not in idl_type.deserializer)): ctxt.add_not_custom_scalar_serialization_not_supported_error(idl_type, syntax_type, idl_type.name, bson_type) if (idl_type.serializer is not None): ctxt.add_not_custom_scalar_serialization_not_supported_error(idl_type, syntax_type, idl_type.name, bson_type) elif (idl_type.deserializer is None): ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name, 'deserializer') _validate_cpp_type(ctxt, idl_type, syntax_type)<|docstring|>Validate each type or field is correct.<|endoftext|>