id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
24,800 | SystemRDL/systemrdl-compiler | systemrdl/node.py | Node.find_by_path | def find_by_path(self, path):
"""
Finds the descendant node that is located at the relative path
Returns ``None`` if not found
Raises exception if path is malformed, or array index is out of range
Parameters
----------
path: str
Path to target relative to current node
Returns
-------
:class:`~Node` or None
Descendant Node. None if not found.
Raises
------
ValueError
If path syntax is invalid
IndexError
If an array index in the path is invalid
"""
pathparts = path.split('.')
current_node = self
for pathpart in pathparts:
m = re.fullmatch(r'^(\w+)((?:\[(?:\d+|0[xX][\da-fA-F]+)\])*)$', pathpart)
if not m:
raise ValueError("Invalid path")
inst_name, array_suffix = m.group(1,2)
idx_list = [ int(s,0) for s in re.findall(r'\[(\d+|0[xX][\da-fA-F]+)\]', array_suffix) ]
current_node = current_node.get_child_by_name(inst_name)
if current_node is None:
return None
if idx_list:
if (isinstance(current_node, AddressableNode)) and current_node.inst.is_array:
# is an array
if len(idx_list) != len(current_node.inst.array_dimensions):
raise IndexError("Wrong number of array dimensions")
current_node.current_idx = [] # pylint: disable=attribute-defined-outside-init
for i,idx in enumerate(idx_list):
if idx >= current_node.inst.array_dimensions[i]:
raise IndexError("Array index out of range")
current_node.current_idx.append(idx)
else:
raise IndexError("Index attempted on non-array component")
return current_node | python | def find_by_path(self, path):
pathparts = path.split('.')
current_node = self
for pathpart in pathparts:
m = re.fullmatch(r'^(\w+)((?:\[(?:\d+|0[xX][\da-fA-F]+)\])*)$', pathpart)
if not m:
raise ValueError("Invalid path")
inst_name, array_suffix = m.group(1,2)
idx_list = [ int(s,0) for s in re.findall(r'\[(\d+|0[xX][\da-fA-F]+)\]', array_suffix) ]
current_node = current_node.get_child_by_name(inst_name)
if current_node is None:
return None
if idx_list:
if (isinstance(current_node, AddressableNode)) and current_node.inst.is_array:
# is an array
if len(idx_list) != len(current_node.inst.array_dimensions):
raise IndexError("Wrong number of array dimensions")
current_node.current_idx = [] # pylint: disable=attribute-defined-outside-init
for i,idx in enumerate(idx_list):
if idx >= current_node.inst.array_dimensions[i]:
raise IndexError("Array index out of range")
current_node.current_idx.append(idx)
else:
raise IndexError("Index attempted on non-array component")
return current_node | [
"def",
"find_by_path",
"(",
"self",
",",
"path",
")",
":",
"pathparts",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"current_node",
"=",
"self",
"for",
"pathpart",
"in",
"pathparts",
":",
"m",
"=",
"re",
".",
"fullmatch",
"(",
"r'^(\\w+)((?:\\[(?:\\d+|0[xX... | Finds the descendant node that is located at the relative path
Returns ``None`` if not found
Raises exception if path is malformed, or array index is out of range
Parameters
----------
path: str
Path to target relative to current node
Returns
-------
:class:`~Node` or None
Descendant Node. None if not found.
Raises
------
ValueError
If path syntax is invalid
IndexError
If an array index in the path is invalid | [
"Finds",
"the",
"descendant",
"node",
"that",
"is",
"located",
"at",
"the",
"relative",
"path",
"Returns",
"None",
"if",
"not",
"found",
"Raises",
"exception",
"if",
"path",
"is",
"malformed",
"or",
"array",
"index",
"is",
"out",
"of",
"range"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L228-L278 |
24,801 | SystemRDL/systemrdl-compiler | systemrdl/node.py | Node.get_property | def get_property(self, prop_name, **kwargs):
"""
Gets the SystemRDL component property
If a property was not explicitly set in the RDL source, its default
value is derived. In some cases, a default value is implied according to
other property values.
Properties values that are a reference to a component instance are
converted to a :class:`~Node` overlay object.
Parameters
----------
prop_name: str
SystemRDL property name
default:
Override built-in default value of property.
If the property was not explicitly set, return this value rather than
the property's intrinsic default value.
Raises
------
LookupError
If prop_name is invalid
"""
ovr_default = False
default = None
if 'default' in kwargs:
ovr_default = True
default = kwargs.pop('default')
# Check for stray kwargs
if kwargs:
raise TypeError("got an unexpected keyword argument '%s'" % list(kwargs.keys())[0])
# If its already in the component, then safe to bypass checks
if prop_name in self.inst.properties:
prop_value = self.inst.properties[prop_name]
if isinstance(prop_value, rdltypes.ComponentRef):
# If this is a hierarchical component reference, convert it to a Node reference
prop_value = prop_value.build_node_ref(self, self.env)
if isinstance(prop_value, rdltypes.PropertyReference):
prop_value._resolve_node(self)
return prop_value
if ovr_default:
# Default value is being overridden by user. Return their value
return default
# Otherwise, return its default value based on the property's rules
rule = self.env.property_rules.lookup_property(prop_name)
# Is it even a valid property or allowed for this component type?
if rule is None:
raise LookupError("Unknown property '%s'" % prop_name)
if type(self.inst) not in rule.bindable_to:
raise LookupError("Unknown property '%s'" % prop_name)
# Return the default value as specified by the rulebook
return rule.get_default(self) | python | def get_property(self, prop_name, **kwargs):
ovr_default = False
default = None
if 'default' in kwargs:
ovr_default = True
default = kwargs.pop('default')
# Check for stray kwargs
if kwargs:
raise TypeError("got an unexpected keyword argument '%s'" % list(kwargs.keys())[0])
# If its already in the component, then safe to bypass checks
if prop_name in self.inst.properties:
prop_value = self.inst.properties[prop_name]
if isinstance(prop_value, rdltypes.ComponentRef):
# If this is a hierarchical component reference, convert it to a Node reference
prop_value = prop_value.build_node_ref(self, self.env)
if isinstance(prop_value, rdltypes.PropertyReference):
prop_value._resolve_node(self)
return prop_value
if ovr_default:
# Default value is being overridden by user. Return their value
return default
# Otherwise, return its default value based on the property's rules
rule = self.env.property_rules.lookup_property(prop_name)
# Is it even a valid property or allowed for this component type?
if rule is None:
raise LookupError("Unknown property '%s'" % prop_name)
if type(self.inst) not in rule.bindable_to:
raise LookupError("Unknown property '%s'" % prop_name)
# Return the default value as specified by the rulebook
return rule.get_default(self) | [
"def",
"get_property",
"(",
"self",
",",
"prop_name",
",",
"*",
"*",
"kwargs",
")",
":",
"ovr_default",
"=",
"False",
"default",
"=",
"None",
"if",
"'default'",
"in",
"kwargs",
":",
"ovr_default",
"=",
"True",
"default",
"=",
"kwargs",
".",
"pop",
"(",
... | Gets the SystemRDL component property
If a property was not explicitly set in the RDL source, its default
value is derived. In some cases, a default value is implied according to
other property values.
Properties values that are a reference to a component instance are
converted to a :class:`~Node` overlay object.
Parameters
----------
prop_name: str
SystemRDL property name
default:
Override built-in default value of property.
If the property was not explicitly set, return this value rather than
the property's intrinsic default value.
Raises
------
LookupError
If prop_name is invalid | [
"Gets",
"the",
"SystemRDL",
"component",
"property"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L281-L343 |
24,802 | SystemRDL/systemrdl-compiler | systemrdl/node.py | Node.list_properties | def list_properties(self, list_all=False):
"""
Lists properties associated with this node.
By default, only lists properties that were explicitly set. If ``list_all`` is
set to ``True`` then lists all valid properties of this component type
Parameters
----------
list_all: bool
If true, lists all valid properties of this component type.
"""
if list_all:
props = []
for k,v in self.env.property_rules.rdl_properties.items():
if type(self.inst) in v.bindable_to:
props.append(k)
for k,v in self.env.property_rules.user_properties.items():
if type(self.inst) in v.bindable_to:
props.append(k)
return props
else:
return list(self.inst.properties.keys()) | python | def list_properties(self, list_all=False):
if list_all:
props = []
for k,v in self.env.property_rules.rdl_properties.items():
if type(self.inst) in v.bindable_to:
props.append(k)
for k,v in self.env.property_rules.user_properties.items():
if type(self.inst) in v.bindable_to:
props.append(k)
return props
else:
return list(self.inst.properties.keys()) | [
"def",
"list_properties",
"(",
"self",
",",
"list_all",
"=",
"False",
")",
":",
"if",
"list_all",
":",
"props",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"env",
".",
"property_rules",
".",
"rdl_properties",
".",
"items",
"(",
")",
":",
... | Lists properties associated with this node.
By default, only lists properties that were explicitly set. If ``list_all`` is
set to ``True`` then lists all valid properties of this component type
Parameters
----------
list_all: bool
If true, lists all valid properties of this component type. | [
"Lists",
"properties",
"associated",
"with",
"this",
"node",
".",
"By",
"default",
"only",
"lists",
"properties",
"that",
"were",
"explicitly",
"set",
".",
"If",
"list_all",
"is",
"set",
"to",
"True",
"then",
"lists",
"all",
"valid",
"properties",
"of",
"thi... | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L346-L368 |
24,803 | SystemRDL/systemrdl-compiler | systemrdl/node.py | Node.get_path | def get_path(self, hier_separator=".", array_suffix="[{index:d}]", empty_array_suffix="[]"):
"""
Generate an absolute path string to this node
Parameters
----------
hier_separator: str
Override the hierarchy separator
array_suffix: str
Override how array suffixes are represented when the index is known
empty_array_suffix: str
Override how array suffixes are represented when the index is not known
"""
if self.parent and not isinstance(self.parent, RootNode):
return(
self.parent.get_path(hier_separator, array_suffix, empty_array_suffix)
+ hier_separator
+ self.get_path_segment(array_suffix, empty_array_suffix)
)
else:
return self.get_path_segment(array_suffix, empty_array_suffix) | python | def get_path(self, hier_separator=".", array_suffix="[{index:d}]", empty_array_suffix="[]"):
if self.parent and not isinstance(self.parent, RootNode):
return(
self.parent.get_path(hier_separator, array_suffix, empty_array_suffix)
+ hier_separator
+ self.get_path_segment(array_suffix, empty_array_suffix)
)
else:
return self.get_path_segment(array_suffix, empty_array_suffix) | [
"def",
"get_path",
"(",
"self",
",",
"hier_separator",
"=",
"\".\"",
",",
"array_suffix",
"=",
"\"[{index:d}]\"",
",",
"empty_array_suffix",
"=",
"\"[]\"",
")",
":",
"if",
"self",
".",
"parent",
"and",
"not",
"isinstance",
"(",
"self",
".",
"parent",
",",
... | Generate an absolute path string to this node
Parameters
----------
hier_separator: str
Override the hierarchy separator
array_suffix: str
Override how array suffixes are represented when the index is known
empty_array_suffix: str
Override how array suffixes are represented when the index is not known | [
"Generate",
"an",
"absolute",
"path",
"string",
"to",
"this",
"node"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L387-L407 |
24,804 | SystemRDL/systemrdl-compiler | systemrdl/node.py | Node.get_html_desc | def get_html_desc(self, markdown_inst=None):
"""
Translates the node's 'desc' property into HTML.
Any RDLFormatCode tags used in the description are converted to HTML.
The text is also fed through a Markdown processor.
The additional Markdown processing allows designers the choice to use a
more modern lightweight markup language as an alternative to SystemRDL's
"RDLFormatCode".
Parameters
----------
markdown_inst: ``markdown.Markdown``
Override the class instance of the Markdown processor.
See the `Markdown module <https://python-markdown.github.io/reference/#Markdown>`_
for more details.
Returns
-------
str or None
HTML formatted string.
If node does not have a description, returns ``None``
"""
desc_str = self.get_property("desc")
if desc_str is None:
return None
return rdlformatcode.rdlfc_to_html(desc_str, self, md=markdown_inst) | python | def get_html_desc(self, markdown_inst=None):
desc_str = self.get_property("desc")
if desc_str is None:
return None
return rdlformatcode.rdlfc_to_html(desc_str, self, md=markdown_inst) | [
"def",
"get_html_desc",
"(",
"self",
",",
"markdown_inst",
"=",
"None",
")",
":",
"desc_str",
"=",
"self",
".",
"get_property",
"(",
"\"desc\"",
")",
"if",
"desc_str",
"is",
"None",
":",
"return",
"None",
"return",
"rdlformatcode",
".",
"rdlfc_to_html",
"(",... | Translates the node's 'desc' property into HTML.
Any RDLFormatCode tags used in the description are converted to HTML.
The text is also fed through a Markdown processor.
The additional Markdown processing allows designers the choice to use a
more modern lightweight markup language as an alternative to SystemRDL's
"RDLFormatCode".
Parameters
----------
markdown_inst: ``markdown.Markdown``
Override the class instance of the Markdown processor.
See the `Markdown module <https://python-markdown.github.io/reference/#Markdown>`_
for more details.
Returns
-------
str or None
HTML formatted string.
If node does not have a description, returns ``None`` | [
"Translates",
"the",
"node",
"s",
"desc",
"property",
"into",
"HTML",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L409-L437 |
24,805 | SystemRDL/systemrdl-compiler | systemrdl/node.py | AddressableNode.address_offset | def address_offset(self):
"""
Byte address offset of this node relative to it's parent
If this node is an array, it's index must be known
Raises
------
ValueError
If this property is referenced on a node whose array index is not
fully defined
"""
if self.inst.is_array:
if self.current_idx is None:
raise ValueError("Index of array element must be known to derive address")
# Calculate the "flattened" index of a general multidimensional array
# For example, a component array declared as:
# foo[S0][S1][S2]
# and referenced as:
# foo[I0][I1][I2]
# Is flattened like this:
# idx = I0*S1*S2 + I1*S2 + I2
idx = 0
for i in range(len(self.current_idx)):
sz = 1
for j in range(i+1, len(self.inst.array_dimensions)):
sz *= self.inst.array_dimensions[j]
idx += sz * self.current_idx[i]
offset = self.inst.addr_offset + idx * self.inst.array_stride
else:
offset = self.inst.addr_offset
return offset | python | def address_offset(self):
if self.inst.is_array:
if self.current_idx is None:
raise ValueError("Index of array element must be known to derive address")
# Calculate the "flattened" index of a general multidimensional array
# For example, a component array declared as:
# foo[S0][S1][S2]
# and referenced as:
# foo[I0][I1][I2]
# Is flattened like this:
# idx = I0*S1*S2 + I1*S2 + I2
idx = 0
for i in range(len(self.current_idx)):
sz = 1
for j in range(i+1, len(self.inst.array_dimensions)):
sz *= self.inst.array_dimensions[j]
idx += sz * self.current_idx[i]
offset = self.inst.addr_offset + idx * self.inst.array_stride
else:
offset = self.inst.addr_offset
return offset | [
"def",
"address_offset",
"(",
"self",
")",
":",
"if",
"self",
".",
"inst",
".",
"is_array",
":",
"if",
"self",
".",
"current_idx",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Index of array element must be known to derive address\"",
")",
"# Calculate the \"fl... | Byte address offset of this node relative to it's parent
If this node is an array, it's index must be known
Raises
------
ValueError
If this property is referenced on a node whose array index is not
fully defined | [
"Byte",
"address",
"offset",
"of",
"this",
"node",
"relative",
"to",
"it",
"s",
"parent"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L496-L531 |
24,806 | SystemRDL/systemrdl-compiler | systemrdl/node.py | AddressableNode.absolute_address | def absolute_address(self):
"""
Get the absolute byte address of this node.
Indexes of all arrays in the node's lineage must be known
Raises
------
ValueError
If this property is referenced on a node whose array lineage is not
fully defined
"""
if self.parent and not isinstance(self.parent, RootNode):
return self.parent.absolute_address + self.address_offset
else:
return self.address_offset | python | def absolute_address(self):
if self.parent and not isinstance(self.parent, RootNode):
return self.parent.absolute_address + self.address_offset
else:
return self.address_offset | [
"def",
"absolute_address",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
"and",
"not",
"isinstance",
"(",
"self",
".",
"parent",
",",
"RootNode",
")",
":",
"return",
"self",
".",
"parent",
".",
"absolute_address",
"+",
"self",
".",
"address_offset",
... | Get the absolute byte address of this node.
Indexes of all arrays in the node's lineage must be known
Raises
------
ValueError
If this property is referenced on a node whose array lineage is not
fully defined | [
"Get",
"the",
"absolute",
"byte",
"address",
"of",
"this",
"node",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L535-L551 |
24,807 | SystemRDL/systemrdl-compiler | systemrdl/node.py | RootNode.top | def top(self):
"""
Returns the top-level addrmap node
"""
for child in self.children(skip_not_present=False):
if not isinstance(child, AddrmapNode):
continue
return child
raise RuntimeError | python | def top(self):
for child in self.children(skip_not_present=False):
if not isinstance(child, AddrmapNode):
continue
return child
raise RuntimeError | [
"def",
"top",
"(",
"self",
")",
":",
"for",
"child",
"in",
"self",
".",
"children",
"(",
"skip_not_present",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"child",
",",
"AddrmapNode",
")",
":",
"continue",
"return",
"child",
"raise",
"RuntimeEr... | Returns the top-level addrmap node | [
"Returns",
"the",
"top",
"-",
"level",
"addrmap",
"node"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L653-L661 |
24,808 | SystemRDL/systemrdl-compiler | systemrdl/node.py | FieldNode.is_sw_writable | def is_sw_writable(self):
"""
Field is writable by software
"""
sw = self.get_property('sw')
return sw in (rdltypes.AccessType.rw, rdltypes.AccessType.rw1,
rdltypes.AccessType.w, rdltypes.AccessType.w1) | python | def is_sw_writable(self):
sw = self.get_property('sw')
return sw in (rdltypes.AccessType.rw, rdltypes.AccessType.rw1,
rdltypes.AccessType.w, rdltypes.AccessType.w1) | [
"def",
"is_sw_writable",
"(",
"self",
")",
":",
"sw",
"=",
"self",
".",
"get_property",
"(",
"'sw'",
")",
"return",
"sw",
"in",
"(",
"rdltypes",
".",
"AccessType",
".",
"rw",
",",
"rdltypes",
".",
"AccessType",
".",
"rw1",
",",
"rdltypes",
".",
"Access... | Field is writable by software | [
"Field",
"is",
"writable",
"by",
"software"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L696-L703 |
24,809 | SystemRDL/systemrdl-compiler | systemrdl/node.py | FieldNode.is_sw_readable | def is_sw_readable(self):
"""
Field is readable by software
"""
sw = self.get_property('sw')
return sw in (rdltypes.AccessType.rw, rdltypes.AccessType.rw1,
rdltypes.AccessType.r) | python | def is_sw_readable(self):
sw = self.get_property('sw')
return sw in (rdltypes.AccessType.rw, rdltypes.AccessType.rw1,
rdltypes.AccessType.r) | [
"def",
"is_sw_readable",
"(",
"self",
")",
":",
"sw",
"=",
"self",
".",
"get_property",
"(",
"'sw'",
")",
"return",
"sw",
"in",
"(",
"rdltypes",
".",
"AccessType",
".",
"rw",
",",
"rdltypes",
".",
"AccessType",
".",
"rw1",
",",
"rdltypes",
".",
"Access... | Field is readable by software | [
"Field",
"is",
"readable",
"by",
"software"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L706-L713 |
24,810 | SystemRDL/systemrdl-compiler | systemrdl/node.py | FieldNode.implements_storage | def implements_storage(self):
"""
True if combination of field access properties imply that the field
implements a storage element.
"""
# 9.4.1, Table 12
sw = self.get_property('sw')
hw = self.get_property('hw')
if sw in (rdltypes.AccessType.rw, rdltypes.AccessType.rw1):
# Software can read and write, implying a storage element
return True
if hw == rdltypes.AccessType.rw:
# Hardware can read and write, implying a storage element
return True
if (sw in (rdltypes.AccessType.w, rdltypes.AccessType.w1)) and (hw == rdltypes.AccessType.r):
# Write-only register visible to hardware is stored
return True
onread = self.get_property('onread')
if onread is not None:
# 9.6.1-c: Onread side-effects imply storage regardless of whether
# or not the field is writable by sw
return True
if self.get_property('hwset') or self.get_property('hwclr'):
# Not in spec, but these imply that a storage element exists
return True
return False | python | def implements_storage(self):
# 9.4.1, Table 12
sw = self.get_property('sw')
hw = self.get_property('hw')
if sw in (rdltypes.AccessType.rw, rdltypes.AccessType.rw1):
# Software can read and write, implying a storage element
return True
if hw == rdltypes.AccessType.rw:
# Hardware can read and write, implying a storage element
return True
if (sw in (rdltypes.AccessType.w, rdltypes.AccessType.w1)) and (hw == rdltypes.AccessType.r):
# Write-only register visible to hardware is stored
return True
onread = self.get_property('onread')
if onread is not None:
# 9.6.1-c: Onread side-effects imply storage regardless of whether
# or not the field is writable by sw
return True
if self.get_property('hwset') or self.get_property('hwclr'):
# Not in spec, but these imply that a storage element exists
return True
return False | [
"def",
"implements_storage",
"(",
"self",
")",
":",
"# 9.4.1, Table 12",
"sw",
"=",
"self",
".",
"get_property",
"(",
"'sw'",
")",
"hw",
"=",
"self",
".",
"get_property",
"(",
"'hw'",
")",
"if",
"sw",
"in",
"(",
"rdltypes",
".",
"AccessType",
".",
"rw",
... | True if combination of field access properties imply that the field
implements a storage element. | [
"True",
"if",
"combination",
"of",
"field",
"access",
"properties",
"imply",
"that",
"the",
"field",
"implements",
"a",
"storage",
"element",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/node.py#L716-L747 |
24,811 | SystemRDL/systemrdl-compiler | systemrdl/core/ComponentVisitor.py | ComponentVisitor.visitComponent_def | def visitComponent_def(self, ctx:SystemRDLParser.Component_defContext):
"""
Create, and possibly instantiate a component
"""
# Get definition. Returns Component
if ctx.component_anon_def() is not None:
comp_def = self.visit(ctx.component_anon_def())
elif ctx.component_named_def() is not None:
comp_def = self.visit(ctx.component_named_def())
else:
raise RuntimeError
comp_def.parent_scope = self.component
if ctx.component_insts() is not None:
if isinstance(self, RootVisitor) and isinstance(comp_def, comp.Addrmap):
self.msg.warning(
"Non-standard instantiation of an addrmap in root namespace will be ignored",
SourceRef.from_antlr(ctx.component_insts().component_inst(0).ID())
)
else:
# Component is instantiated one or more times
if ctx.component_inst_type() is not None:
inst_type = self.visit(ctx.component_inst_type())
else:
inst_type = None
# Pass some temporary info to visitComponent_insts
self._tmp = (comp_def, inst_type, None)
self.visit(ctx.component_insts())
return None | python | def visitComponent_def(self, ctx:SystemRDLParser.Component_defContext):
# Get definition. Returns Component
if ctx.component_anon_def() is not None:
comp_def = self.visit(ctx.component_anon_def())
elif ctx.component_named_def() is not None:
comp_def = self.visit(ctx.component_named_def())
else:
raise RuntimeError
comp_def.parent_scope = self.component
if ctx.component_insts() is not None:
if isinstance(self, RootVisitor) and isinstance(comp_def, comp.Addrmap):
self.msg.warning(
"Non-standard instantiation of an addrmap in root namespace will be ignored",
SourceRef.from_antlr(ctx.component_insts().component_inst(0).ID())
)
else:
# Component is instantiated one or more times
if ctx.component_inst_type() is not None:
inst_type = self.visit(ctx.component_inst_type())
else:
inst_type = None
# Pass some temporary info to visitComponent_insts
self._tmp = (comp_def, inst_type, None)
self.visit(ctx.component_insts())
return None | [
"def",
"visitComponent_def",
"(",
"self",
",",
"ctx",
":",
"SystemRDLParser",
".",
"Component_defContext",
")",
":",
"# Get definition. Returns Component",
"if",
"ctx",
".",
"component_anon_def",
"(",
")",
"is",
"not",
"None",
":",
"comp_def",
"=",
"self",
".",
... | Create, and possibly instantiate a component | [
"Create",
"and",
"possibly",
"instantiate",
"a",
"component"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/ComponentVisitor.py#L76-L108 |
24,812 | SystemRDL/systemrdl-compiler | systemrdl/core/ComponentVisitor.py | ComponentVisitor.define_component | def define_component(self, body, type_token, def_name, param_defs):
"""
Given component definition, recurse to another ComponentVisitor
to define a new component
"""
for subclass in ComponentVisitor.__subclasses__():
if subclass.comp_type == self._CompType_Map[type_token.type]:
visitor = subclass(self.compiler, def_name, param_defs)
return visitor.visit(body)
raise RuntimeError | python | def define_component(self, body, type_token, def_name, param_defs):
for subclass in ComponentVisitor.__subclasses__():
if subclass.comp_type == self._CompType_Map[type_token.type]:
visitor = subclass(self.compiler, def_name, param_defs)
return visitor.visit(body)
raise RuntimeError | [
"def",
"define_component",
"(",
"self",
",",
"body",
",",
"type_token",
",",
"def_name",
",",
"param_defs",
")",
":",
"for",
"subclass",
"in",
"ComponentVisitor",
".",
"__subclasses__",
"(",
")",
":",
"if",
"subclass",
".",
"comp_type",
"==",
"self",
".",
... | Given component definition, recurse to another ComponentVisitor
to define a new component | [
"Given",
"component",
"definition",
"recurse",
"to",
"another",
"ComponentVisitor",
"to",
"define",
"a",
"new",
"component"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/ComponentVisitor.py#L153-L162 |
24,813 | SystemRDL/systemrdl-compiler | systemrdl/core/ComponentVisitor.py | ComponentVisitor.get_instance_assignment | def get_instance_assignment(self, ctx):
"""
Gets the integer expression in any of the four instance assignment
operators ('=' '@' '+=' '%=')
"""
if ctx is None:
return None
visitor = ExprVisitor(self.compiler)
expr = visitor.visit(ctx.expr())
expr = expressions.AssignmentCast(self.compiler.env, SourceRef.from_antlr(ctx.op), expr, int)
expr.predict_type()
return expr | python | def get_instance_assignment(self, ctx):
if ctx is None:
return None
visitor = ExprVisitor(self.compiler)
expr = visitor.visit(ctx.expr())
expr = expressions.AssignmentCast(self.compiler.env, SourceRef.from_antlr(ctx.op), expr, int)
expr.predict_type()
return expr | [
"def",
"get_instance_assignment",
"(",
"self",
",",
"ctx",
")",
":",
"if",
"ctx",
"is",
"None",
":",
"return",
"None",
"visitor",
"=",
"ExprVisitor",
"(",
"self",
".",
"compiler",
")",
"expr",
"=",
"visitor",
".",
"visit",
"(",
"ctx",
".",
"expr",
"(",... | Gets the integer expression in any of the four instance assignment
operators ('=' '@' '+=' '%=') | [
"Gets",
"the",
"integer",
"expression",
"in",
"any",
"of",
"the",
"four",
"instance",
"assignment",
"operators",
"(",
"="
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/ComponentVisitor.py#L311-L323 |
24,814 | SystemRDL/systemrdl-compiler | systemrdl/core/ComponentVisitor.py | ComponentVisitor.visitParam_def | def visitParam_def(self, ctx:SystemRDLParser.Param_defContext):
"""
Parameter Definition block
"""
self.compiler.namespace.enter_scope()
param_defs = []
for elem in ctx.getTypedRuleContexts(SystemRDLParser.Param_def_elemContext):
param_def = self.visit(elem)
param_defs.append(param_def)
self.compiler.namespace.exit_scope()
return param_defs | python | def visitParam_def(self, ctx:SystemRDLParser.Param_defContext):
self.compiler.namespace.enter_scope()
param_defs = []
for elem in ctx.getTypedRuleContexts(SystemRDLParser.Param_def_elemContext):
param_def = self.visit(elem)
param_defs.append(param_def)
self.compiler.namespace.exit_scope()
return param_defs | [
"def",
"visitParam_def",
"(",
"self",
",",
"ctx",
":",
"SystemRDLParser",
".",
"Param_defContext",
")",
":",
"self",
".",
"compiler",
".",
"namespace",
".",
"enter_scope",
"(",
")",
"param_defs",
"=",
"[",
"]",
"for",
"elem",
"in",
"ctx",
".",
"getTypedRul... | Parameter Definition block | [
"Parameter",
"Definition",
"block"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/ComponentVisitor.py#L471-L483 |
24,815 | SystemRDL/systemrdl-compiler | systemrdl/core/ComponentVisitor.py | ComponentVisitor.visitParam_def_elem | def visitParam_def_elem(self, ctx:SystemRDLParser.Param_def_elemContext):
"""
Individual parameter definition elements
"""
# Construct parameter type
data_type_token = self.visit(ctx.data_type())
param_data_type = self.datatype_from_token(data_type_token)
if ctx.array_type_suffix() is None:
# Non-array type
param_type = param_data_type
else:
# Array-like type
param_type = rdltypes.ArrayPlaceholder(param_data_type)
# Get parameter name
param_name = get_ID_text(ctx.ID())
# Get expression for parameter default, if any
if ctx.expr() is not None:
visitor = ExprVisitor(self.compiler)
default_expr = visitor.visit(ctx.expr())
default_expr = expressions.AssignmentCast(self.compiler.env, SourceRef.from_antlr(ctx.ID()), default_expr, param_type)
default_expr.predict_type()
else:
default_expr = None
# Create Parameter object
param = Parameter(param_type, param_name, default_expr)
# Register it in the parameter def namespace scope
self.compiler.namespace.register_element(param_name, param, None, SourceRef.from_antlr(ctx.ID()))
return param | python | def visitParam_def_elem(self, ctx:SystemRDLParser.Param_def_elemContext):
# Construct parameter type
data_type_token = self.visit(ctx.data_type())
param_data_type = self.datatype_from_token(data_type_token)
if ctx.array_type_suffix() is None:
# Non-array type
param_type = param_data_type
else:
# Array-like type
param_type = rdltypes.ArrayPlaceholder(param_data_type)
# Get parameter name
param_name = get_ID_text(ctx.ID())
# Get expression for parameter default, if any
if ctx.expr() is not None:
visitor = ExprVisitor(self.compiler)
default_expr = visitor.visit(ctx.expr())
default_expr = expressions.AssignmentCast(self.compiler.env, SourceRef.from_antlr(ctx.ID()), default_expr, param_type)
default_expr.predict_type()
else:
default_expr = None
# Create Parameter object
param = Parameter(param_type, param_name, default_expr)
# Register it in the parameter def namespace scope
self.compiler.namespace.register_element(param_name, param, None, SourceRef.from_antlr(ctx.ID()))
return param | [
"def",
"visitParam_def_elem",
"(",
"self",
",",
"ctx",
":",
"SystemRDLParser",
".",
"Param_def_elemContext",
")",
":",
"# Construct parameter type",
"data_type_token",
"=",
"self",
".",
"visit",
"(",
"ctx",
".",
"data_type",
"(",
")",
")",
"param_data_type",
"=",
... | Individual parameter definition elements | [
"Individual",
"parameter",
"definition",
"elements"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/ComponentVisitor.py#L485-L518 |
24,816 | SystemRDL/systemrdl-compiler | systemrdl/core/BaseVisitor.py | BaseVisitor.datatype_from_token | def datatype_from_token(self, token):
"""
Given a SystemRDLParser token, lookup the type
This only includes types under the "data_type" grammar rule
"""
if token.type == SystemRDLParser.ID:
# Is an identifier for either an enum or struct type
typ = self.compiler.namespace.lookup_type(get_ID_text(token))
if typ is None:
self.msg.fatal(
"Type '%s' is not defined" % get_ID_text(token),
SourceRef.from_antlr(token)
)
if rdltypes.is_user_enum(typ) or rdltypes.is_user_struct(typ):
return typ
else:
self.msg.fatal(
"Type '%s' is not a struct or enum" % get_ID_text(token),
SourceRef.from_antlr(token)
)
else:
return self._DataType_Map[token.type] | python | def datatype_from_token(self, token):
if token.type == SystemRDLParser.ID:
# Is an identifier for either an enum or struct type
typ = self.compiler.namespace.lookup_type(get_ID_text(token))
if typ is None:
self.msg.fatal(
"Type '%s' is not defined" % get_ID_text(token),
SourceRef.from_antlr(token)
)
if rdltypes.is_user_enum(typ) or rdltypes.is_user_struct(typ):
return typ
else:
self.msg.fatal(
"Type '%s' is not a struct or enum" % get_ID_text(token),
SourceRef.from_antlr(token)
)
else:
return self._DataType_Map[token.type] | [
"def",
"datatype_from_token",
"(",
"self",
",",
"token",
")",
":",
"if",
"token",
".",
"type",
"==",
"SystemRDLParser",
".",
"ID",
":",
"# Is an identifier for either an enum or struct type",
"typ",
"=",
"self",
".",
"compiler",
".",
"namespace",
".",
"lookup_type... | Given a SystemRDLParser token, lookup the type
This only includes types under the "data_type" grammar rule | [
"Given",
"a",
"SystemRDLParser",
"token",
"lookup",
"the",
"type",
"This",
"only",
"includes",
"types",
"under",
"the",
"data_type",
"grammar",
"rule"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/BaseVisitor.py#L29-L54 |
24,817 | SystemRDL/systemrdl-compiler | systemrdl/rdltypes.py | get_rdltype | def get_rdltype(value):
"""
Given a value, return the type identifier object used within the RDL compiler
If not a supported type, return None
"""
if isinstance(value, (int, bool, str)):
# Pass canonical types as-is
return type(value)
elif is_user_enum(type(value)):
return type(value)
elif is_user_struct(type(value)):
return type(value)
elif isinstance(value, enum.Enum):
return type(value)
elif isinstance(value, list):
# Create ArrayPlaceholder representation
# Determine element type and make sure it is uniform
array_el_type = None
for el in value:
el_type = get_rdltype(el)
if el_type is None:
return None
if (array_el_type is not None) and (el_type != array_el_type):
return None
array_el_type = el_type
return ArrayPlaceholder(array_el_type)
else:
return None | python | def get_rdltype(value):
if isinstance(value, (int, bool, str)):
# Pass canonical types as-is
return type(value)
elif is_user_enum(type(value)):
return type(value)
elif is_user_struct(type(value)):
return type(value)
elif isinstance(value, enum.Enum):
return type(value)
elif isinstance(value, list):
# Create ArrayPlaceholder representation
# Determine element type and make sure it is uniform
array_el_type = None
for el in value:
el_type = get_rdltype(el)
if el_type is None:
return None
if (array_el_type is not None) and (el_type != array_el_type):
return None
array_el_type = el_type
return ArrayPlaceholder(array_el_type)
else:
return None | [
"def",
"get_rdltype",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"bool",
",",
"str",
")",
")",
":",
"# Pass canonical types as-is",
"return",
"type",
"(",
"value",
")",
"elif",
"is_user_enum",
"(",
"type",
"(",
"value... | Given a value, return the type identifier object used within the RDL compiler
If not a supported type, return None | [
"Given",
"a",
"value",
"return",
"the",
"type",
"identifier",
"object",
"used",
"within",
"the",
"RDL",
"compiler",
"If",
"not",
"a",
"supported",
"type",
"return",
"None"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/rdltypes.py#L507-L536 |
24,818 | SystemRDL/systemrdl-compiler | systemrdl/rdltypes.py | UserEnum.get_html_desc | def get_html_desc(self, markdown_inst=None):
"""
Translates the enum's 'desc' property into HTML.
Any RDLFormatCode tags used in the description are converted to HTML.
The text is also fed through a Markdown processor.
The additional Markdown processing allows designers the choice to use a
more modern lightweight markup language as an alternative to SystemRDL's
"RDLFormatCode".
Parameters
----------
markdown_inst: ``markdown.Markdown``
Override the class instance of the Markdown processor.
See the `Markdown module <https://python-markdown.github.io/reference/#Markdown>`_
for more details.
Returns
-------
str or None
HTML formatted string.
If node does not have a description, returns ``None``
"""
desc_str = self._rdl_desc_
if desc_str is None:
return None
return rdlformatcode.rdlfc_to_html(desc_str, md=markdown_inst) | python | def get_html_desc(self, markdown_inst=None):
desc_str = self._rdl_desc_
if desc_str is None:
return None
return rdlformatcode.rdlfc_to_html(desc_str, md=markdown_inst) | [
"def",
"get_html_desc",
"(",
"self",
",",
"markdown_inst",
"=",
"None",
")",
":",
"desc_str",
"=",
"self",
".",
"_rdl_desc_",
"if",
"desc_str",
"is",
"None",
":",
"return",
"None",
"return",
"rdlformatcode",
".",
"rdlfc_to_html",
"(",
"desc_str",
",",
"md",
... | Translates the enum's 'desc' property into HTML.
Any RDLFormatCode tags used in the description are converted to HTML.
The text is also fed through a Markdown processor.
The additional Markdown processing allows designers the choice to use a
more modern lightweight markup language as an alternative to SystemRDL's
"RDLFormatCode".
Parameters
----------
markdown_inst: ``markdown.Markdown``
Override the class instance of the Markdown processor.
See the `Markdown module <https://python-markdown.github.io/reference/#Markdown>`_
for more details.
Returns
-------
str or None
HTML formatted string.
If node does not have a description, returns ``None`` | [
"Translates",
"the",
"enum",
"s",
"desc",
"property",
"into",
"HTML",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/rdltypes.py#L147-L174 |
24,819 | SystemRDL/systemrdl-compiler | systemrdl/rdltypes.py | UserEnum.get_scope_path | def get_scope_path(cls, scope_separator="::"):
"""
Generate a string that represents this enum's declaration namespace
scope.
Parameters
----------
scope_separator: str
Override the separator between namespace scopes
"""
if cls.get_parent_scope() is None:
return ""
elif isinstance(cls.get_parent_scope(), comp.Root):
return ""
else:
parent_path = cls.get_parent_scope().get_scope_path(scope_separator)
if parent_path:
return(
parent_path
+ scope_separator
+ cls.get_parent_scope().type_name
)
else:
return cls.get_parent_scope().type_name | python | def get_scope_path(cls, scope_separator="::"):
if cls.get_parent_scope() is None:
return ""
elif isinstance(cls.get_parent_scope(), comp.Root):
return ""
else:
parent_path = cls.get_parent_scope().get_scope_path(scope_separator)
if parent_path:
return(
parent_path
+ scope_separator
+ cls.get_parent_scope().type_name
)
else:
return cls.get_parent_scope().type_name | [
"def",
"get_scope_path",
"(",
"cls",
",",
"scope_separator",
"=",
"\"::\"",
")",
":",
"if",
"cls",
".",
"get_parent_scope",
"(",
")",
"is",
"None",
":",
"return",
"\"\"",
"elif",
"isinstance",
"(",
"cls",
".",
"get_parent_scope",
"(",
")",
",",
"comp",
"... | Generate a string that represents this enum's declaration namespace
scope.
Parameters
----------
scope_separator: str
Override the separator between namespace scopes | [
"Generate",
"a",
"string",
"that",
"represents",
"this",
"enum",
"s",
"declaration",
"namespace",
"scope",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/rdltypes.py#L188-L211 |
24,820 | SystemRDL/systemrdl-compiler | systemrdl/rdltypes.py | UserStruct.define_new | def define_new(cls, name, members, is_abstract=False):
"""
Define a new struct type derived from the current type.
Parameters
----------
name: str
Name of the struct type
members: {member_name : type}
Dictionary of struct member types.
is_abstract: bool
If set, marks the struct as abstract.
"""
m = OrderedDict(cls._members)
# Make sure derivation does not have any overlapping keys with its parent
if set(m.keys()) & set(members.keys()):
raise ValueError("'members' contains keys that overlap with parent")
m.update(members)
dct = {
'_members' : m,
'_is_abstract': is_abstract,
}
newcls = type(name, (cls,), dct)
return newcls | python | def define_new(cls, name, members, is_abstract=False):
m = OrderedDict(cls._members)
# Make sure derivation does not have any overlapping keys with its parent
if set(m.keys()) & set(members.keys()):
raise ValueError("'members' contains keys that overlap with parent")
m.update(members)
dct = {
'_members' : m,
'_is_abstract': is_abstract,
}
newcls = type(name, (cls,), dct)
return newcls | [
"def",
"define_new",
"(",
"cls",
",",
"name",
",",
"members",
",",
"is_abstract",
"=",
"False",
")",
":",
"m",
"=",
"OrderedDict",
"(",
"cls",
".",
"_members",
")",
"# Make sure derivation does not have any overlapping keys with its parent",
"if",
"set",
"(",
"m",... | Define a new struct type derived from the current type.
Parameters
----------
name: str
Name of the struct type
members: {member_name : type}
Dictionary of struct member types.
is_abstract: bool
If set, marks the struct as abstract. | [
"Define",
"a",
"new",
"struct",
"type",
"derived",
"from",
"the",
"current",
"type",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/rdltypes.py#L288-L314 |
24,821 | SystemRDL/systemrdl-compiler | systemrdl/compiler.py | RDLCompiler.define_udp | def define_udp(self, name, valid_type, valid_components=None, default=None):
"""
Pre-define a user-defined property.
This is the equivalent to the following RDL:
.. code-block:: none
property <name> {
type = <valid_type>;
component = <valid_components>;
default = <default>
};
Parameters
----------
name: str
Property name
valid_components: list
List of :class:`~systemrdl.component.Component` types the UDP can be bound to.
If None, then UDP can be bound to all components.
valid_type: type
Assignment type that this UDP will enforce
default:
Default if a value is not specified when the UDP is bound to a component.
Value must be compatible with ``valid_type``
"""
if valid_components is None:
valid_components = [
comp.Field,
comp.Reg,
comp.Regfile,
comp.Addrmap,
comp.Mem,
comp.Signal,
#TODO constraint,
]
if name in self.env.property_rules.rdl_properties:
raise ValueError("name '%s' conflicts with existing built-in RDL property")
udp = UserProperty(self.env, name, valid_components, [valid_type], default)
self.env.property_rules.user_properties[udp.name] = udp | python | def define_udp(self, name, valid_type, valid_components=None, default=None):
if valid_components is None:
valid_components = [
comp.Field,
comp.Reg,
comp.Regfile,
comp.Addrmap,
comp.Mem,
comp.Signal,
#TODO constraint,
]
if name in self.env.property_rules.rdl_properties:
raise ValueError("name '%s' conflicts with existing built-in RDL property")
udp = UserProperty(self.env, name, valid_components, [valid_type], default)
self.env.property_rules.user_properties[udp.name] = udp | [
"def",
"define_udp",
"(",
"self",
",",
"name",
",",
"valid_type",
",",
"valid_components",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"if",
"valid_components",
"is",
"None",
":",
"valid_components",
"=",
"[",
"comp",
".",
"Field",
",",
"comp",
"... | Pre-define a user-defined property.
This is the equivalent to the following RDL:
.. code-block:: none
property <name> {
type = <valid_type>;
component = <valid_components>;
default = <default>
};
Parameters
----------
name: str
Property name
valid_components: list
List of :class:`~systemrdl.component.Component` types the UDP can be bound to.
If None, then UDP can be bound to all components.
valid_type: type
Assignment type that this UDP will enforce
default:
Default if a value is not specified when the UDP is bound to a component.
Value must be compatible with ``valid_type`` | [
"Pre",
"-",
"define",
"a",
"user",
"-",
"defined",
"property",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/compiler.py#L47-L91 |
24,822 | SystemRDL/systemrdl-compiler | systemrdl/compiler.py | RDLCompiler.compile_file | def compile_file(self, path, incl_search_paths=None):
"""
Parse & compile a single file and append it to RDLCompiler's root
namespace.
If any exceptions (:class:`~systemrdl.RDLCompileError` or other)
occur during compilation, then the RDLCompiler object should be discarded.
Parameters
----------
path:str
Path to an RDL source file
incl_search_paths:list
List of additional paths to search to resolve includes.
If unset, defaults to an empty list.
Relative include paths are resolved in the following order:
1. Search each path specified in ``incl_search_paths``.
2. Path relative to the source file performing the include.
Raises
------
:class:`~systemrdl.RDLCompileError`
If any fatal compile error is encountered.
"""
if incl_search_paths is None:
incl_search_paths = []
fpp = preprocessor.FilePreprocessor(self.env, path, incl_search_paths)
preprocessed_text, seg_map = fpp.preprocess()
input_stream = preprocessor.PreprocessedInputStream(preprocessed_text, seg_map)
lexer = SystemRDLLexer(input_stream)
lexer.removeErrorListeners()
lexer.addErrorListener(messages.RDLAntlrErrorListener(self.msg))
token_stream = CommonTokenStream(lexer)
parser = SystemRDLParser(token_stream)
parser.removeErrorListeners()
parser.addErrorListener(messages.RDLAntlrErrorListener(self.msg))
# Run Antlr parser on input
parsed_tree = parser.root()
if self.msg.had_error:
self.msg.fatal("Parse aborted due to previous errors")
# Traverse parse tree with RootVisitor
self.visitor.visit(parsed_tree)
# Reset default property assignments from namespace.
# They should not be shared between files since that would be confusing.
self.namespace.default_property_ns_stack = [{}]
if self.msg.had_error:
self.msg.fatal("Compile aborted due to previous errors") | python | def compile_file(self, path, incl_search_paths=None):
if incl_search_paths is None:
incl_search_paths = []
fpp = preprocessor.FilePreprocessor(self.env, path, incl_search_paths)
preprocessed_text, seg_map = fpp.preprocess()
input_stream = preprocessor.PreprocessedInputStream(preprocessed_text, seg_map)
lexer = SystemRDLLexer(input_stream)
lexer.removeErrorListeners()
lexer.addErrorListener(messages.RDLAntlrErrorListener(self.msg))
token_stream = CommonTokenStream(lexer)
parser = SystemRDLParser(token_stream)
parser.removeErrorListeners()
parser.addErrorListener(messages.RDLAntlrErrorListener(self.msg))
# Run Antlr parser on input
parsed_tree = parser.root()
if self.msg.had_error:
self.msg.fatal("Parse aborted due to previous errors")
# Traverse parse tree with RootVisitor
self.visitor.visit(parsed_tree)
# Reset default property assignments from namespace.
# They should not be shared between files since that would be confusing.
self.namespace.default_property_ns_stack = [{}]
if self.msg.had_error:
self.msg.fatal("Compile aborted due to previous errors") | [
"def",
"compile_file",
"(",
"self",
",",
"path",
",",
"incl_search_paths",
"=",
"None",
")",
":",
"if",
"incl_search_paths",
"is",
"None",
":",
"incl_search_paths",
"=",
"[",
"]",
"fpp",
"=",
"preprocessor",
".",
"FilePreprocessor",
"(",
"self",
".",
"env",
... | Parse & compile a single file and append it to RDLCompiler's root
namespace.
If any exceptions (:class:`~systemrdl.RDLCompileError` or other)
occur during compilation, then the RDLCompiler object should be discarded.
Parameters
----------
path:str
Path to an RDL source file
incl_search_paths:list
List of additional paths to search to resolve includes.
If unset, defaults to an empty list.
Relative include paths are resolved in the following order:
1. Search each path specified in ``incl_search_paths``.
2. Path relative to the source file performing the include.
Raises
------
:class:`~systemrdl.RDLCompileError`
If any fatal compile error is encountered. | [
"Parse",
"&",
"compile",
"a",
"single",
"file",
"and",
"append",
"it",
"to",
"RDLCompiler",
"s",
"root",
"namespace",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/compiler.py#L94-L152 |
24,823 | SystemRDL/systemrdl-compiler | systemrdl/compiler.py | RDLCompiler.elaborate | def elaborate(self, top_def_name=None, inst_name=None, parameters=None):
"""
Elaborates the design for the given top-level addrmap component.
During elaboration, the following occurs:
- An instance of the ``$root`` meta-component is created.
- The addrmap component specified by ``top_def_name`` is instantiated as a
child of ``$root``.
- Expressions, parameters, and inferred address/field placements are elaborated.
- Validation checks are performed.
If a design contains multiple root-level addrmaps, ``elaborate()`` can be
called multiple times in order to elaborate each individually.
If any exceptions (:class:`~systemrdl.RDLCompileError` or other)
occur during elaboration, then the RDLCompiler object should be discarded.
Parameters
----------
top_def_name: str
Explicitly choose which addrmap in the root namespace will be the
top-level component.
If unset, The last addrmap defined will be chosen.
inst_name: str
Overrides the top-component's instantiated name.
By default, instantiated name is the same as ``top_def_name``
parameters: dict
Dictionary of parameter overrides for the top component instance.
Raises
------
:class:`~systemrdl.RDLCompileError`
If any fatal elaboration error is encountered
Returns
-------
:class:`~systemrdl.node.RootNode`
Elaborated root meta-component's Node object.
"""
if parameters is None:
parameters = {}
# Get top-level component definition to elaborate
if top_def_name is not None:
# Lookup top_def_name
if top_def_name not in self.root.comp_defs:
self.msg.fatal("Elaboration target '%s' not found" % top_def_name)
top_def = self.root.comp_defs[top_def_name]
if not isinstance(top_def, comp.Addrmap):
self.msg.fatal("Elaboration target '%s' is not an 'addrmap' component" % top_def_name)
else:
# Not specified. Find the last addrmap defined
for comp_def in reversed(list(self.root.comp_defs.values())):
if isinstance(comp_def, comp.Addrmap):
top_def = comp_def
top_def_name = comp_def.type_name
break
else:
self.msg.fatal("Could not find any 'addrmap' components to elaborate")
# Create an instance of the root component
root_inst = deepcopy(self.root)
root_inst.is_instance = True
root_inst.original_def = self.root
root_inst.inst_name = "$root"
# Create a top-level instance
top_inst = deepcopy(top_def)
top_inst.is_instance = True
top_inst.original_def = top_def
top_inst.addr_offset = 0
top_inst.external = True # addrmap is always implied as external
if inst_name is not None:
top_inst.inst_name = inst_name
else:
top_inst.inst_name = top_def_name
# Override parameters as needed
for param_name, value in parameters.items():
# Find the parameter to override
parameter = None
for p in top_inst.parameters:
if p.name == param_name:
parameter = p
break
else:
raise ValueError("Parameter '%s' is not available for override" % param_name)
value_expr = expr.ExternalLiteral(self.env, value)
value_type = value_expr.predict_type()
if value_type is None:
raise TypeError("Override value for parameter '%s' is an unrecognized type" % param_name)
if value_type != parameter.param_type:
raise TypeError("Incorrect type for parameter '%s'" % param_name)
parameter.expr = value_expr
# instantiate top_inst into the root component instance
root_inst.children.append(top_inst)
root_node = RootNode(root_inst, self.env, None)
# Resolve all expressions
walker.RDLWalker(skip_not_present=False).walk(
root_node,
ElabExpressionsListener(self.msg)
)
# Resolve address and field placement
walker.RDLWalker(skip_not_present=False).walk(
root_node,
PrePlacementValidateListener(self.msg),
StructuralPlacementListener(self.msg),
LateElabListener(self.msg)
)
# Validate design
# Only need to validate nodes that are present
walker.RDLWalker(skip_not_present=True).walk(root_node, ValidateListener(self.env))
if self.msg.had_error:
self.msg.fatal("Elaborate aborted due to previous errors")
return root_node | python | def elaborate(self, top_def_name=None, inst_name=None, parameters=None):
if parameters is None:
parameters = {}
# Get top-level component definition to elaborate
if top_def_name is not None:
# Lookup top_def_name
if top_def_name not in self.root.comp_defs:
self.msg.fatal("Elaboration target '%s' not found" % top_def_name)
top_def = self.root.comp_defs[top_def_name]
if not isinstance(top_def, comp.Addrmap):
self.msg.fatal("Elaboration target '%s' is not an 'addrmap' component" % top_def_name)
else:
# Not specified. Find the last addrmap defined
for comp_def in reversed(list(self.root.comp_defs.values())):
if isinstance(comp_def, comp.Addrmap):
top_def = comp_def
top_def_name = comp_def.type_name
break
else:
self.msg.fatal("Could not find any 'addrmap' components to elaborate")
# Create an instance of the root component
root_inst = deepcopy(self.root)
root_inst.is_instance = True
root_inst.original_def = self.root
root_inst.inst_name = "$root"
# Create a top-level instance
top_inst = deepcopy(top_def)
top_inst.is_instance = True
top_inst.original_def = top_def
top_inst.addr_offset = 0
top_inst.external = True # addrmap is always implied as external
if inst_name is not None:
top_inst.inst_name = inst_name
else:
top_inst.inst_name = top_def_name
# Override parameters as needed
for param_name, value in parameters.items():
# Find the parameter to override
parameter = None
for p in top_inst.parameters:
if p.name == param_name:
parameter = p
break
else:
raise ValueError("Parameter '%s' is not available for override" % param_name)
value_expr = expr.ExternalLiteral(self.env, value)
value_type = value_expr.predict_type()
if value_type is None:
raise TypeError("Override value for parameter '%s' is an unrecognized type" % param_name)
if value_type != parameter.param_type:
raise TypeError("Incorrect type for parameter '%s'" % param_name)
parameter.expr = value_expr
# instantiate top_inst into the root component instance
root_inst.children.append(top_inst)
root_node = RootNode(root_inst, self.env, None)
# Resolve all expressions
walker.RDLWalker(skip_not_present=False).walk(
root_node,
ElabExpressionsListener(self.msg)
)
# Resolve address and field placement
walker.RDLWalker(skip_not_present=False).walk(
root_node,
PrePlacementValidateListener(self.msg),
StructuralPlacementListener(self.msg),
LateElabListener(self.msg)
)
# Validate design
# Only need to validate nodes that are present
walker.RDLWalker(skip_not_present=True).walk(root_node, ValidateListener(self.env))
if self.msg.had_error:
self.msg.fatal("Elaborate aborted due to previous errors")
return root_node | [
"def",
"elaborate",
"(",
"self",
",",
"top_def_name",
"=",
"None",
",",
"inst_name",
"=",
"None",
",",
"parameters",
"=",
"None",
")",
":",
"if",
"parameters",
"is",
"None",
":",
"parameters",
"=",
"{",
"}",
"# Get top-level component definition to elaborate",
... | Elaborates the design for the given top-level addrmap component.
During elaboration, the following occurs:
- An instance of the ``$root`` meta-component is created.
- The addrmap component specified by ``top_def_name`` is instantiated as a
child of ``$root``.
- Expressions, parameters, and inferred address/field placements are elaborated.
- Validation checks are performed.
If a design contains multiple root-level addrmaps, ``elaborate()`` can be
called multiple times in order to elaborate each individually.
If any exceptions (:class:`~systemrdl.RDLCompileError` or other)
occur during elaboration, then the RDLCompiler object should be discarded.
Parameters
----------
top_def_name: str
Explicitly choose which addrmap in the root namespace will be the
top-level component.
If unset, The last addrmap defined will be chosen.
inst_name: str
Overrides the top-component's instantiated name.
By default, instantiated name is the same as ``top_def_name``
parameters: dict
Dictionary of parameter overrides for the top component instance.
Raises
------
:class:`~systemrdl.RDLCompileError`
If any fatal elaboration error is encountered
Returns
-------
:class:`~systemrdl.node.RootNode`
Elaborated root meta-component's Node object. | [
"Elaborates",
"the",
"design",
"for",
"the",
"given",
"top",
"-",
"level",
"addrmap",
"component",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/compiler.py#L154-L285 |
24,824 | SystemRDL/systemrdl-compiler | systemrdl/core/properties.py | PropertyRuleBoolPair.get_default | def get_default(self, node):
"""
If not explicitly set, check if the opposite was set first before returning
default
"""
if self.opposite_property in node.inst.properties:
return not node.inst.properties[self.opposite_property]
else:
return self.default | python | def get_default(self, node):
if self.opposite_property in node.inst.properties:
return not node.inst.properties[self.opposite_property]
else:
return self.default | [
"def",
"get_default",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"opposite_property",
"in",
"node",
".",
"inst",
".",
"properties",
":",
"return",
"not",
"node",
".",
"inst",
".",
"properties",
"[",
"self",
".",
"opposite_property",
"]",
"els... | If not explicitly set, check if the opposite was set first before returning
default | [
"If",
"not",
"explicitly",
"set",
"check",
"if",
"the",
"opposite",
"was",
"set",
"first",
"before",
"returning",
"default"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/properties.py#L165-L173 |
24,825 | SystemRDL/systemrdl-compiler | systemrdl/core/properties.py | Prop_rset.get_default | def get_default(self, node):
"""
If not explicitly set, check if onread sets the equivalent
"""
if node.inst.properties.get("onread", None) == rdltypes.OnReadType.rset:
return True
else:
return self.default | python | def get_default(self, node):
if node.inst.properties.get("onread", None) == rdltypes.OnReadType.rset:
return True
else:
return self.default | [
"def",
"get_default",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"inst",
".",
"properties",
".",
"get",
"(",
"\"onread\"",
",",
"None",
")",
"==",
"rdltypes",
".",
"OnReadType",
".",
"rset",
":",
"return",
"True",
"else",
":",
"return",
"... | If not explicitly set, check if onread sets the equivalent | [
"If",
"not",
"explicitly",
"set",
"check",
"if",
"onread",
"sets",
"the",
"equivalent"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/properties.py#L622-L629 |
24,826 | SystemRDL/systemrdl-compiler | systemrdl/core/properties.py | Prop_onread.assign_value | def assign_value(self, comp_def, value, src_ref):
"""
Overrides other related properties
"""
super().assign_value(comp_def, value, src_ref)
if "rclr" in comp_def.properties:
del comp_def.properties["rclr"]
if "rset" in comp_def.properties:
del comp_def.properties["rset"] | python | def assign_value(self, comp_def, value, src_ref):
super().assign_value(comp_def, value, src_ref)
if "rclr" in comp_def.properties:
del comp_def.properties["rclr"]
if "rset" in comp_def.properties:
del comp_def.properties["rset"] | [
"def",
"assign_value",
"(",
"self",
",",
"comp_def",
",",
"value",
",",
"src_ref",
")",
":",
"super",
"(",
")",
".",
"assign_value",
"(",
"comp_def",
",",
"value",
",",
"src_ref",
")",
"if",
"\"rclr\"",
"in",
"comp_def",
".",
"properties",
":",
"del",
... | Overrides other related properties | [
"Overrides",
"other",
"related",
"properties"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/properties.py#L642-L650 |
24,827 | SystemRDL/systemrdl-compiler | systemrdl/core/properties.py | Prop_onread.get_default | def get_default(self, node):
"""
If not explicitly set, check if rset or rclr imply the value
"""
if node.inst.properties.get("rset", False):
return rdltypes.OnReadType.rset
elif node.inst.properties.get("rclr", False):
return rdltypes.OnReadType.rclr
else:
return self.default | python | def get_default(self, node):
if node.inst.properties.get("rset", False):
return rdltypes.OnReadType.rset
elif node.inst.properties.get("rclr", False):
return rdltypes.OnReadType.rclr
else:
return self.default | [
"def",
"get_default",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"inst",
".",
"properties",
".",
"get",
"(",
"\"rset\"",
",",
"False",
")",
":",
"return",
"rdltypes",
".",
"OnReadType",
".",
"rset",
"elif",
"node",
".",
"inst",
".",
"prop... | If not explicitly set, check if rset or rclr imply the value | [
"If",
"not",
"explicitly",
"set",
"check",
"if",
"rset",
"or",
"rclr",
"imply",
"the",
"value"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/properties.py#L652-L661 |
24,828 | SystemRDL/systemrdl-compiler | systemrdl/core/properties.py | Prop_woclr.get_default | def get_default(self, node):
"""
If not explicitly set, check if onwrite sets the equivalent
"""
if node.inst.properties.get("onwrite", None) == rdltypes.OnWriteType.woclr:
return True
else:
return self.default | python | def get_default(self, node):
if node.inst.properties.get("onwrite", None) == rdltypes.OnWriteType.woclr:
return True
else:
return self.default | [
"def",
"get_default",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"inst",
".",
"properties",
".",
"get",
"(",
"\"onwrite\"",
",",
"None",
")",
"==",
"rdltypes",
".",
"OnWriteType",
".",
"woclr",
":",
"return",
"True",
"else",
":",
"return",
... | If not explicitly set, check if onwrite sets the equivalent | [
"If",
"not",
"explicitly",
"set",
"check",
"if",
"onwrite",
"sets",
"the",
"equivalent"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/properties.py#L702-L709 |
24,829 | SystemRDL/systemrdl-compiler | systemrdl/core/properties.py | Prop_onwrite.get_default | def get_default(self, node):
"""
If not explicitly set, check if woset or woclr imply the value
"""
if node.inst.properties.get("woset", False):
return rdltypes.OnWriteType.woset
elif node.inst.properties.get("woclr", False):
return rdltypes.OnWriteType.woclr
else:
return self.default | python | def get_default(self, node):
if node.inst.properties.get("woset", False):
return rdltypes.OnWriteType.woset
elif node.inst.properties.get("woclr", False):
return rdltypes.OnWriteType.woclr
else:
return self.default | [
"def",
"get_default",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"inst",
".",
"properties",
".",
"get",
"(",
"\"woset\"",
",",
"False",
")",
":",
"return",
"rdltypes",
".",
"OnWriteType",
".",
"woset",
"elif",
"node",
".",
"inst",
".",
"p... | If not explicitly set, check if woset or woclr imply the value | [
"If",
"not",
"explicitly",
"set",
"check",
"if",
"woset",
"or",
"woclr",
"imply",
"the",
"value"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/properties.py#L762-L771 |
24,830 | SystemRDL/systemrdl-compiler | systemrdl/core/properties.py | Prop_threshold.assign_value | def assign_value(self, comp_def, value, src_ref):
"""
Set both alias and actual value
"""
super().assign_value(comp_def, value, src_ref)
comp_def.properties['incrthreshold'] = value | python | def assign_value(self, comp_def, value, src_ref):
super().assign_value(comp_def, value, src_ref)
comp_def.properties['incrthreshold'] = value | [
"def",
"assign_value",
"(",
"self",
",",
"comp_def",
",",
"value",
",",
"src_ref",
")",
":",
"super",
"(",
")",
".",
"assign_value",
"(",
"comp_def",
",",
"value",
",",
"src_ref",
")",
"comp_def",
".",
"properties",
"[",
"'incrthreshold'",
"]",
"=",
"val... | Set both alias and actual value | [
"Set",
"both",
"alias",
"and",
"actual",
"value"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/properties.py#L1008-L1013 |
24,831 | SystemRDL/systemrdl-compiler | systemrdl/core/properties.py | Prop_stickybit.get_default | def get_default(self, node):
"""
Unless specified otherwise, intr fields are implicitly stickybit
"""
if node.inst.properties.get("intr", False):
# Interrupt is set!
# Default is implicitly stickybit, unless the mutually-exclusive
# sticky property was set instead
return not node.inst.properties.get("sticky", False)
else:
return False | python | def get_default(self, node):
if node.inst.properties.get("intr", False):
# Interrupt is set!
# Default is implicitly stickybit, unless the mutually-exclusive
# sticky property was set instead
return not node.inst.properties.get("sticky", False)
else:
return False | [
"def",
"get_default",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"inst",
".",
"properties",
".",
"get",
"(",
"\"intr\"",
",",
"False",
")",
":",
"# Interrupt is set!",
"# Default is implicitly stickybit, unless the mutually-exclusive",
"# sticky property w... | Unless specified otherwise, intr fields are implicitly stickybit | [
"Unless",
"specified",
"otherwise",
"intr",
"fields",
"are",
"implicitly",
"stickybit"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/properties.py#L1198-L1208 |
24,832 | SystemRDL/systemrdl-compiler | systemrdl/core/elaborate.py | StructuralPlacementListener.resolve_addresses | def resolve_addresses(self, node):
"""
Resolve addresses of children of Addrmap and Regfile components
"""
# Get alignment based on 'alignment' property
# This remains constant for all children
prop_alignment = self.alignment_stack[-1]
if prop_alignment is None:
# was not specified. Does not contribute to alignment
prop_alignment = 1
prev_node = None
for child_node in node.children(skip_not_present=False):
if not isinstance(child_node, AddressableNode):
continue
if child_node.inst.addr_offset is not None:
# Address is already known. Do not need to infer
prev_node = child_node
continue
if node.env.chk_implicit_addr:
node.env.msg.message(
node.env.chk_implicit_addr,
"Address offset of component '%s' is not explicitly set" % child_node.inst.inst_name,
child_node.inst.inst_src_ref
)
# Get alignment specified by '%=' allocator, if any
alloc_alignment = child_node.inst.addr_align
if alloc_alignment is None:
# was not specified. Does not contribute to alignment
alloc_alignment = 1
# Calculate alignment based on current addressing mode
if self.addressing_mode_stack[-1] == rdltypes.AddressingType.compact:
if isinstance(child_node, RegNode):
# Regs are aligned based on their accesswidth
mode_alignment = child_node.get_property('accesswidth') // 8
else:
# Spec does not specify for other components
# Assuming absolutely compact packing
mode_alignment = 1
elif self.addressing_mode_stack[-1] == rdltypes.AddressingType.regalign:
# Components are aligned to a multiple of their size
# Spec vaguely suggests that alignment is also a power of 2
mode_alignment = child_node.size
mode_alignment = roundup_pow2(mode_alignment)
elif self.addressing_mode_stack[-1] == rdltypes.AddressingType.fullalign:
# Same as regalign except for arrays
# Arrays are aligned to their total size
# Both are rounded to power of 2
mode_alignment = child_node.total_size
mode_alignment = roundup_pow2(mode_alignment)
else:
raise RuntimeError
# Calculate resulting address offset
alignment = max(prop_alignment, alloc_alignment, mode_alignment)
if prev_node is None:
next_offset = 0
else:
next_offset = prev_node.inst.addr_offset + prev_node.total_size
# round next_offset up to alignment
child_node.inst.addr_offset = roundup_to(next_offset, alignment)
prev_node = child_node
# Sort children by address offset
# Non-addressable child components are sorted to be first (signals)
def get_child_sort_key(inst):
if not isinstance(inst, comp.AddressableComponent):
return -1
else:
return inst.addr_offset
node.inst.children.sort(key=get_child_sort_key) | python | def resolve_addresses(self, node):
# Get alignment based on 'alignment' property
# This remains constant for all children
prop_alignment = self.alignment_stack[-1]
if prop_alignment is None:
# was not specified. Does not contribute to alignment
prop_alignment = 1
prev_node = None
for child_node in node.children(skip_not_present=False):
if not isinstance(child_node, AddressableNode):
continue
if child_node.inst.addr_offset is not None:
# Address is already known. Do not need to infer
prev_node = child_node
continue
if node.env.chk_implicit_addr:
node.env.msg.message(
node.env.chk_implicit_addr,
"Address offset of component '%s' is not explicitly set" % child_node.inst.inst_name,
child_node.inst.inst_src_ref
)
# Get alignment specified by '%=' allocator, if any
alloc_alignment = child_node.inst.addr_align
if alloc_alignment is None:
# was not specified. Does not contribute to alignment
alloc_alignment = 1
# Calculate alignment based on current addressing mode
if self.addressing_mode_stack[-1] == rdltypes.AddressingType.compact:
if isinstance(child_node, RegNode):
# Regs are aligned based on their accesswidth
mode_alignment = child_node.get_property('accesswidth') // 8
else:
# Spec does not specify for other components
# Assuming absolutely compact packing
mode_alignment = 1
elif self.addressing_mode_stack[-1] == rdltypes.AddressingType.regalign:
# Components are aligned to a multiple of their size
# Spec vaguely suggests that alignment is also a power of 2
mode_alignment = child_node.size
mode_alignment = roundup_pow2(mode_alignment)
elif self.addressing_mode_stack[-1] == rdltypes.AddressingType.fullalign:
# Same as regalign except for arrays
# Arrays are aligned to their total size
# Both are rounded to power of 2
mode_alignment = child_node.total_size
mode_alignment = roundup_pow2(mode_alignment)
else:
raise RuntimeError
# Calculate resulting address offset
alignment = max(prop_alignment, alloc_alignment, mode_alignment)
if prev_node is None:
next_offset = 0
else:
next_offset = prev_node.inst.addr_offset + prev_node.total_size
# round next_offset up to alignment
child_node.inst.addr_offset = roundup_to(next_offset, alignment)
prev_node = child_node
# Sort children by address offset
# Non-addressable child components are sorted to be first (signals)
def get_child_sort_key(inst):
if not isinstance(inst, comp.AddressableComponent):
return -1
else:
return inst.addr_offset
node.inst.children.sort(key=get_child_sort_key) | [
"def",
"resolve_addresses",
"(",
"self",
",",
"node",
")",
":",
"# Get alignment based on 'alignment' property",
"# This remains constant for all children",
"prop_alignment",
"=",
"self",
".",
"alignment_stack",
"[",
"-",
"1",
"]",
"if",
"prop_alignment",
"is",
"None",
... | Resolve addresses of children of Addrmap and Regfile components | [
"Resolve",
"addresses",
"of",
"children",
"of",
"Addrmap",
"and",
"Regfile",
"components"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/elaborate.py#L408-L488 |
24,833 | SystemRDL/systemrdl-compiler | systemrdl/core/helpers.py | get_ID_text | def get_ID_text(token):
"""
Get the text from the ID token.
Strips off leading slash escape if present
"""
if isinstance(token, CommonToken):
text = token.text
else:
text = token.getText()
text = text.lstrip('\\')
return text | python | def get_ID_text(token):
if isinstance(token, CommonToken):
text = token.text
else:
text = token.getText()
text = text.lstrip('\\')
return text | [
"def",
"get_ID_text",
"(",
"token",
")",
":",
"if",
"isinstance",
"(",
"token",
",",
"CommonToken",
")",
":",
"text",
"=",
"token",
".",
"text",
"else",
":",
"text",
"=",
"token",
".",
"getText",
"(",
")",
"text",
"=",
"text",
".",
"lstrip",
"(",
"... | Get the text from the ID token.
Strips off leading slash escape if present | [
"Get",
"the",
"text",
"from",
"the",
"ID",
"token",
".",
"Strips",
"off",
"leading",
"slash",
"escape",
"if",
"present"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/helpers.py#L16-L27 |
24,834 | SystemRDL/systemrdl-compiler | systemrdl/preprocessor/segment_map.py | SegmentMap.derive_source_offset | def derive_source_offset(self, offset, is_end=False):
"""
Given a post-preprocessed coordinate, derives the corresponding coordinate
in the original source file.
Returns result in the following tuple:
(src_offset, src_path, include_ref)
where:
- src_offset is the translated coordinate
If the input offset lands on a macro expansion, then src_offset
returns the start or end coordinate according to is_end
- src_path points to the original source file
- include_ref describes any `include lineage using a IncludeRef object
Is none if file was not referenced via include
"""
for segment in self.segments:
if offset <= segment.end:
if isinstance(segment, MacroSegment):
if is_end:
return (
segment.src_end,
segment.src,
segment.incl_ref
)
else:
return (
segment.src_start,
segment.src,
segment.incl_ref
)
else:
return (
segment.src_start + (offset - segment.start),
segment.src,
segment.incl_ref
)
# Reached end. Assume end of last segment
return (
self.segments[-1].src_end,
self.segments[-1].src,
self.segments[-1].incl_ref
) | python | def derive_source_offset(self, offset, is_end=False):
for segment in self.segments:
if offset <= segment.end:
if isinstance(segment, MacroSegment):
if is_end:
return (
segment.src_end,
segment.src,
segment.incl_ref
)
else:
return (
segment.src_start,
segment.src,
segment.incl_ref
)
else:
return (
segment.src_start + (offset - segment.start),
segment.src,
segment.incl_ref
)
# Reached end. Assume end of last segment
return (
self.segments[-1].src_end,
self.segments[-1].src,
self.segments[-1].incl_ref
) | [
"def",
"derive_source_offset",
"(",
"self",
",",
"offset",
",",
"is_end",
"=",
"False",
")",
":",
"for",
"segment",
"in",
"self",
".",
"segments",
":",
"if",
"offset",
"<=",
"segment",
".",
"end",
":",
"if",
"isinstance",
"(",
"segment",
",",
"MacroSegme... | Given a post-preprocessed coordinate, derives the corresponding coordinate
in the original source file.
Returns result in the following tuple:
(src_offset, src_path, include_ref)
where:
- src_offset is the translated coordinate
If the input offset lands on a macro expansion, then src_offset
returns the start or end coordinate according to is_end
- src_path points to the original source file
- include_ref describes any `include lineage using a IncludeRef object
Is none if file was not referenced via include | [
"Given",
"a",
"post",
"-",
"preprocessed",
"coordinate",
"derives",
"the",
"corresponding",
"coordinate",
"in",
"the",
"original",
"source",
"file",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/preprocessor/segment_map.py#L8-L50 |
24,835 | SystemRDL/systemrdl-compiler | systemrdl/preprocessor/preprocessor.py | FilePreprocessor.preprocess | def preprocess(self):
"""
Run preprocessor on a top-level file.
Performs the following preprocess steps:
- Expand `include directives
- Perl Preprocessor
Returns
-------
tuple
(preprocessed_text, SegmentMap)
"""
tokens = self.tokenize()
pl_segments, has_perl_tags = self.get_perl_segments(tokens)
# Generate flattened output
str_parts = []
smap = segment_map.SegmentMap()
offset = 0
if has_perl_tags:
# Needs to be processed through perl interpreter
emit_list = self.run_perl_miniscript(pl_segments)
for entry in emit_list:
if entry['type'] == "ref":
pl_seg = pl_segments[entry['ref']]
emit_text = pl_seg.get_text()
map_seg = segment_map.UnalteredSegment(
offset, offset + len(emit_text) - 1,
pl_seg.start, pl_seg.end, pl_seg.file_pp.path,
pl_seg.file_pp.incl_ref
)
offset += len(emit_text)
smap.segments.append(map_seg)
str_parts.append(emit_text)
elif entry['type'] == "text":
pl_seg = pl_segments[entry['ref']]
emit_text = entry['text']
map_seg = segment_map.MacroSegment(
offset, offset + len(emit_text) - 1,
pl_seg.start, pl_seg.end, pl_seg.file_pp.path,
pl_seg.file_pp.incl_ref
)
offset += len(emit_text)
smap.segments.append(map_seg)
str_parts.append(emit_text)
else:
# OK to bypass perl interpreter
for pl_seg in pl_segments:
emit_text = pl_seg.get_text()
map_seg = segment_map.UnalteredSegment(
offset, offset + len(emit_text) - 1,
pl_seg.start, pl_seg.end, pl_seg.file_pp.path,
pl_seg.file_pp.incl_ref
)
offset += len(emit_text)
smap.segments.append(map_seg)
str_parts.append(emit_text)
#segment_map.print_segment_debug("".join(str_parts), smap)
return ("".join(str_parts), smap) | python | def preprocess(self):
tokens = self.tokenize()
pl_segments, has_perl_tags = self.get_perl_segments(tokens)
# Generate flattened output
str_parts = []
smap = segment_map.SegmentMap()
offset = 0
if has_perl_tags:
# Needs to be processed through perl interpreter
emit_list = self.run_perl_miniscript(pl_segments)
for entry in emit_list:
if entry['type'] == "ref":
pl_seg = pl_segments[entry['ref']]
emit_text = pl_seg.get_text()
map_seg = segment_map.UnalteredSegment(
offset, offset + len(emit_text) - 1,
pl_seg.start, pl_seg.end, pl_seg.file_pp.path,
pl_seg.file_pp.incl_ref
)
offset += len(emit_text)
smap.segments.append(map_seg)
str_parts.append(emit_text)
elif entry['type'] == "text":
pl_seg = pl_segments[entry['ref']]
emit_text = entry['text']
map_seg = segment_map.MacroSegment(
offset, offset + len(emit_text) - 1,
pl_seg.start, pl_seg.end, pl_seg.file_pp.path,
pl_seg.file_pp.incl_ref
)
offset += len(emit_text)
smap.segments.append(map_seg)
str_parts.append(emit_text)
else:
# OK to bypass perl interpreter
for pl_seg in pl_segments:
emit_text = pl_seg.get_text()
map_seg = segment_map.UnalteredSegment(
offset, offset + len(emit_text) - 1,
pl_seg.start, pl_seg.end, pl_seg.file_pp.path,
pl_seg.file_pp.incl_ref
)
offset += len(emit_text)
smap.segments.append(map_seg)
str_parts.append(emit_text)
#segment_map.print_segment_debug("".join(str_parts), smap)
return ("".join(str_parts), smap) | [
"def",
"preprocess",
"(",
"self",
")",
":",
"tokens",
"=",
"self",
".",
"tokenize",
"(",
")",
"pl_segments",
",",
"has_perl_tags",
"=",
"self",
".",
"get_perl_segments",
"(",
"tokens",
")",
"# Generate flattened output",
"str_parts",
"=",
"[",
"]",
"smap",
"... | Run preprocessor on a top-level file.
Performs the following preprocess steps:
- Expand `include directives
- Perl Preprocessor
Returns
-------
tuple
(preprocessed_text, SegmentMap) | [
"Run",
"preprocessor",
"on",
"a",
"top",
"-",
"level",
"file",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/preprocessor/preprocessor.py#L26-L93 |
24,836 | SystemRDL/systemrdl-compiler | systemrdl/preprocessor/preprocessor.py | FilePreprocessor.tokenize | def tokenize(self):
"""
Tokenize the input text
Scans for instances of perl tags and include directives.
Tokenization skips line and block comments.
Returns
-------
list
List of tuples: (typ, start, end)
Where:
- typ is "perl" or "incl"
- start/end mark the first/last char offset of the token
"""
tokens = []
token_spec = [
('mlc', r'/\*.*?\*/'),
('slc', r'//[^\r\n]*?\r?\n'),
('perl', r'<%.*?%>'),
('incl', r'`include'),
]
tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_spec)
for m in re.finditer(tok_regex, self.text, re.DOTALL):
if m.lastgroup in ("incl", "perl"):
tokens.append((m.lastgroup, m.start(0), m.end(0)-1))
return tokens | python | def tokenize(self):
tokens = []
token_spec = [
('mlc', r'/\*.*?\*/'),
('slc', r'//[^\r\n]*?\r?\n'),
('perl', r'<%.*?%>'),
('incl', r'`include'),
]
tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_spec)
for m in re.finditer(tok_regex, self.text, re.DOTALL):
if m.lastgroup in ("incl", "perl"):
tokens.append((m.lastgroup, m.start(0), m.end(0)-1))
return tokens | [
"def",
"tokenize",
"(",
"self",
")",
":",
"tokens",
"=",
"[",
"]",
"token_spec",
"=",
"[",
"(",
"'mlc'",
",",
"r'/\\*.*?\\*/'",
")",
",",
"(",
"'slc'",
",",
"r'//[^\\r\\n]*?\\r?\\n'",
")",
",",
"(",
"'perl'",
",",
"r'<%.*?%>'",
")",
",",
"(",
"'incl'",... | Tokenize the input text
Scans for instances of perl tags and include directives.
Tokenization skips line and block comments.
Returns
-------
list
List of tuples: (typ, start, end)
Where:
- typ is "perl" or "incl"
- start/end mark the first/last char offset of the token | [
"Tokenize",
"the",
"input",
"text"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/preprocessor/preprocessor.py#L96-L124 |
24,837 | SystemRDL/systemrdl-compiler | systemrdl/preprocessor/preprocessor.py | FilePreprocessor.parse_include | def parse_include(self, start):
"""
Extract include from text based on start position of token
Returns
-------
(end, incl_path)
- end: last char in include
- incl_path: Resolved path to include
"""
# Seek back to start of line
i = start
while i:
if self.text[i] == '\n':
i += 1
break
i -= 1
line_start = i
# check that there is no unexpected text before the include
if not (self.text[line_start:start] == "" or self.text[line_start:start].isspace()):
self.env.msg.fatal(
"Unexpected text before include",
messages.SourceRef(line_start, start-1, filename=self.path)
)
# Capture include contents
inc_regex = re.compile(r'`include\s+("([^\r\n]+)"|<([^\r\n]+)>)')
m_inc = inc_regex.match(self.text, start)
if m_inc is None:
self.env.msg.fatal(
"Invalid usage of include directive",
messages.SourceRef(start, start+7, filename=self.path)
)
incl_path_raw = m_inc.group(2) or m_inc.group(3)
end = m_inc.end(0)-1
path_start = m_inc.start(1)
#[^\r\n]*?\r?\n
# Check that only comments follow
tail_regex = re.compile(r'(?:[ \t]*/\*[^\r\n]*?\*/)*[ \t]*(?://[^\r\n]*?|/\*[^\r\n]*?)?\r?\n')
if not tail_regex.match(self.text, end+1):
tail_capture_regex = re.compile(r'[^\r\n]*?\r?\n')
m = tail_capture_regex.match(self.text, end+1)
self.env.msg.fatal(
"Unexpected text after include",
messages.SourceRef(end+1, m.end(0)-1, filename=self.path)
)
# Resolve include path.
if os.path.isabs(incl_path_raw):
incl_path = incl_path_raw
else:
# Search include paths first.
for search_path in self.search_paths:
incl_path = os.path.join(search_path, incl_path_raw)
if os.path.isfile(incl_path):
# found match!
break
else:
# Otherwise, assume it is relative to the current file
incl_path = os.path.join(os.path.dirname(self.path), incl_path_raw)
if not os.path.isfile(incl_path):
self.env.msg.fatal(
"Could not find '%s' in include search paths" % incl_path_raw,
messages.SourceRef(path_start, end, filename=self.path)
)
# Check if path has already been referenced before
incl_ref = self.incl_ref
while incl_ref:
if os.path.samefile(incl_path, incl_ref.path):
self.env.msg.fatal(
"Include of '%s' results in a circular reference" % incl_path_raw,
messages.SourceRef(path_start, end, filename=self.path)
)
incl_ref = incl_ref.parent
return(end, incl_path) | python | def parse_include(self, start):
# Seek back to start of line
i = start
while i:
if self.text[i] == '\n':
i += 1
break
i -= 1
line_start = i
# check that there is no unexpected text before the include
if not (self.text[line_start:start] == "" or self.text[line_start:start].isspace()):
self.env.msg.fatal(
"Unexpected text before include",
messages.SourceRef(line_start, start-1, filename=self.path)
)
# Capture include contents
inc_regex = re.compile(r'`include\s+("([^\r\n]+)"|<([^\r\n]+)>)')
m_inc = inc_regex.match(self.text, start)
if m_inc is None:
self.env.msg.fatal(
"Invalid usage of include directive",
messages.SourceRef(start, start+7, filename=self.path)
)
incl_path_raw = m_inc.group(2) or m_inc.group(3)
end = m_inc.end(0)-1
path_start = m_inc.start(1)
#[^\r\n]*?\r?\n
# Check that only comments follow
tail_regex = re.compile(r'(?:[ \t]*/\*[^\r\n]*?\*/)*[ \t]*(?://[^\r\n]*?|/\*[^\r\n]*?)?\r?\n')
if not tail_regex.match(self.text, end+1):
tail_capture_regex = re.compile(r'[^\r\n]*?\r?\n')
m = tail_capture_regex.match(self.text, end+1)
self.env.msg.fatal(
"Unexpected text after include",
messages.SourceRef(end+1, m.end(0)-1, filename=self.path)
)
# Resolve include path.
if os.path.isabs(incl_path_raw):
incl_path = incl_path_raw
else:
# Search include paths first.
for search_path in self.search_paths:
incl_path = os.path.join(search_path, incl_path_raw)
if os.path.isfile(incl_path):
# found match!
break
else:
# Otherwise, assume it is relative to the current file
incl_path = os.path.join(os.path.dirname(self.path), incl_path_raw)
if not os.path.isfile(incl_path):
self.env.msg.fatal(
"Could not find '%s' in include search paths" % incl_path_raw,
messages.SourceRef(path_start, end, filename=self.path)
)
# Check if path has already been referenced before
incl_ref = self.incl_ref
while incl_ref:
if os.path.samefile(incl_path, incl_ref.path):
self.env.msg.fatal(
"Include of '%s' results in a circular reference" % incl_path_raw,
messages.SourceRef(path_start, end, filename=self.path)
)
incl_ref = incl_ref.parent
return(end, incl_path) | [
"def",
"parse_include",
"(",
"self",
",",
"start",
")",
":",
"# Seek back to start of line",
"i",
"=",
"start",
"while",
"i",
":",
"if",
"self",
".",
"text",
"[",
"i",
"]",
"==",
"'\\n'",
":",
"i",
"+=",
"1",
"break",
"i",
"-=",
"1",
"line_start",
"=... | Extract include from text based on start position of token
Returns
-------
(end, incl_path)
- end: last char in include
- incl_path: Resolved path to include | [
"Extract",
"include",
"from",
"text",
"based",
"on",
"start",
"position",
"of",
"token"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/preprocessor/preprocessor.py#L127-L204 |
24,838 | SystemRDL/systemrdl-compiler | systemrdl/preprocessor/preprocessor.py | FilePreprocessor.run_perl_miniscript | def run_perl_miniscript(self, segments):
"""
Generates and runs a perl miniscript that derives the text that will be
emitted from the preprocessor
returns the resulting emit list
"""
# Check if perl is installed
if shutil.which("perl") is None:
self.env.msg.fatal(
"Input contains Perl preprocessor tags, but an installation of Perl could not be found"
)
# Generate minimal perl script that captures activities described in the source file
lines = []
for i,pp_seg in enumerate(segments):
if isinstance(pp_seg, PPPUnalteredSegment):
# Text outside preprocessor tags that should remain unaltered
# Insert command to emit reference to this text segment
lines.append("rdlppp_utils::emit_ref(%d);" % i)
elif isinstance(pp_seg, PPPPerlSegment):
# Perl code snippet. Insert directly
lines.append(pp_seg.get_text())
elif isinstance(pp_seg, PPPMacroSegment):
# Preprocessor macro print tag
# Insert command to store resulting text
var = pp_seg.get_text()
# Check for any illegal characters
if re.match(r'[\s;]', var):
self.env.msg.fatal(
"Invalid text found in Perl macro expansion",
messages.SourceRef(pp_seg.start, pp_seg.end, filename=self.path)
)
lines.append("rdlppp_utils::emit_text(%d, %s);" % (i, var))
miniscript = '\n'.join(lines)
# Run miniscript
result = subprocess_run(
["perl", os.path.join(os.path.dirname(__file__), "ppp_runner.pl")],
input=miniscript.encode("utf-8"),
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
timeout=5
)
if result.returncode:
self.env.msg.fatal(
"Encountered a Perl syntax error while executing embedded Perl preprocessor commands:\n"
+ result.stderr.decode("utf-8"),
# TODO: Fix useless context somehow
messages.SourceRef(filename=self.path)
)
# miniscript returns the emit list in JSON format. Convert it
emit_list = json.loads(result.stdout.decode('utf-8'))
return emit_list | python | def run_perl_miniscript(self, segments):
# Check if perl is installed
if shutil.which("perl") is None:
self.env.msg.fatal(
"Input contains Perl preprocessor tags, but an installation of Perl could not be found"
)
# Generate minimal perl script that captures activities described in the source file
lines = []
for i,pp_seg in enumerate(segments):
if isinstance(pp_seg, PPPUnalteredSegment):
# Text outside preprocessor tags that should remain unaltered
# Insert command to emit reference to this text segment
lines.append("rdlppp_utils::emit_ref(%d);" % i)
elif isinstance(pp_seg, PPPPerlSegment):
# Perl code snippet. Insert directly
lines.append(pp_seg.get_text())
elif isinstance(pp_seg, PPPMacroSegment):
# Preprocessor macro print tag
# Insert command to store resulting text
var = pp_seg.get_text()
# Check for any illegal characters
if re.match(r'[\s;]', var):
self.env.msg.fatal(
"Invalid text found in Perl macro expansion",
messages.SourceRef(pp_seg.start, pp_seg.end, filename=self.path)
)
lines.append("rdlppp_utils::emit_text(%d, %s);" % (i, var))
miniscript = '\n'.join(lines)
# Run miniscript
result = subprocess_run(
["perl", os.path.join(os.path.dirname(__file__), "ppp_runner.pl")],
input=miniscript.encode("utf-8"),
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
timeout=5
)
if result.returncode:
self.env.msg.fatal(
"Encountered a Perl syntax error while executing embedded Perl preprocessor commands:\n"
+ result.stderr.decode("utf-8"),
# TODO: Fix useless context somehow
messages.SourceRef(filename=self.path)
)
# miniscript returns the emit list in JSON format. Convert it
emit_list = json.loads(result.stdout.decode('utf-8'))
return emit_list | [
"def",
"run_perl_miniscript",
"(",
"self",
",",
"segments",
")",
":",
"# Check if perl is installed",
"if",
"shutil",
".",
"which",
"(",
"\"perl\"",
")",
"is",
"None",
":",
"self",
".",
"env",
".",
"msg",
".",
"fatal",
"(",
"\"Input contains Perl preprocessor ta... | Generates and runs a perl miniscript that derives the text that will be
emitted from the preprocessor
returns the resulting emit list | [
"Generates",
"and",
"runs",
"a",
"perl",
"miniscript",
"that",
"derives",
"the",
"text",
"that",
"will",
"be",
"emitted",
"from",
"the",
"preprocessor"
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/preprocessor/preprocessor.py#L264-L323 |
24,839 | SystemRDL/systemrdl-compiler | systemrdl/core/namespace.py | NamespaceRegistry.get_default_properties | def get_default_properties(self, comp_type):
"""
Returns a flattened dictionary of all default property assignments
visible in the current scope that apply to the current component type.
"""
# Flatten out all the default assignments that apply to the current scope
# This does not include any default assignments made within the current
# scope, so exclude those.
props = {}
for scope in self.default_property_ns_stack[:-1]:
props.update(scope)
# filter out properties that are not relevant
prop_names = list(props.keys())
for prop_name in prop_names:
rule = self.env.property_rules.lookup_property(prop_name)
if rule is None:
self.msg.fatal(
"Unrecognized property '%s'" % prop_name,
props[prop_name][0]
)
if comp_type not in rule.bindable_to:
del props[prop_name]
return props | python | def get_default_properties(self, comp_type):
# Flatten out all the default assignments that apply to the current scope
# This does not include any default assignments made within the current
# scope, so exclude those.
props = {}
for scope in self.default_property_ns_stack[:-1]:
props.update(scope)
# filter out properties that are not relevant
prop_names = list(props.keys())
for prop_name in prop_names:
rule = self.env.property_rules.lookup_property(prop_name)
if rule is None:
self.msg.fatal(
"Unrecognized property '%s'" % prop_name,
props[prop_name][0]
)
if comp_type not in rule.bindable_to:
del props[prop_name]
return props | [
"def",
"get_default_properties",
"(",
"self",
",",
"comp_type",
")",
":",
"# Flatten out all the default assignments that apply to the current scope",
"# This does not include any default assignments made within the current",
"# scope, so exclude those.",
"props",
"=",
"{",
"}",
"for",... | Returns a flattened dictionary of all default property assignments
visible in the current scope that apply to the current component type. | [
"Returns",
"a",
"flattened",
"dictionary",
"of",
"all",
"default",
"property",
"assignments",
"visible",
"in",
"the",
"current",
"scope",
"that",
"apply",
"to",
"the",
"current",
"component",
"type",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/namespace.py#L59-L83 |
24,840 | SystemRDL/systemrdl-compiler | systemrdl/component.py | Component.get_scope_path | def get_scope_path(self, scope_separator="::"):
"""
Generate a string that represents this component's declaration namespace
scope.
Parameters
----------
scope_separator: str
Override the separator between namespace scopes
"""
if self.parent_scope is None:
return ""
elif isinstance(self.parent_scope, Root):
return ""
else:
parent_path = self.parent_scope.get_scope_path(scope_separator)
if parent_path:
return(
parent_path
+ scope_separator
+ self.parent_scope.type_name
)
else:
return self.parent_scope.type_name | python | def get_scope_path(self, scope_separator="::"):
if self.parent_scope is None:
return ""
elif isinstance(self.parent_scope, Root):
return ""
else:
parent_path = self.parent_scope.get_scope_path(scope_separator)
if parent_path:
return(
parent_path
+ scope_separator
+ self.parent_scope.type_name
)
else:
return self.parent_scope.type_name | [
"def",
"get_scope_path",
"(",
"self",
",",
"scope_separator",
"=",
"\"::\"",
")",
":",
"if",
"self",
".",
"parent_scope",
"is",
"None",
":",
"return",
"\"\"",
"elif",
"isinstance",
"(",
"self",
".",
"parent_scope",
",",
"Root",
")",
":",
"return",
"\"\"",
... | Generate a string that represents this component's declaration namespace
scope.
Parameters
----------
scope_separator: str
Override the separator between namespace scopes | [
"Generate",
"a",
"string",
"that",
"represents",
"this",
"component",
"s",
"declaration",
"namespace",
"scope",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/component.py#L112-L135 |
24,841 | SystemRDL/systemrdl-compiler | systemrdl/component.py | AddressableComponent.n_elements | def n_elements(self):
"""
Total number of array elements.
If array is multidimensional, array is flattened.
Returns 1 if not an array.
"""
if self.is_array:
return functools.reduce(operator.mul, self.array_dimensions)
else:
return 1 | python | def n_elements(self):
if self.is_array:
return functools.reduce(operator.mul, self.array_dimensions)
else:
return 1 | [
"def",
"n_elements",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_array",
":",
"return",
"functools",
".",
"reduce",
"(",
"operator",
".",
"mul",
",",
"self",
".",
"array_dimensions",
")",
"else",
":",
"return",
"1"
] | Total number of array elements.
If array is multidimensional, array is flattened.
Returns 1 if not an array. | [
"Total",
"number",
"of",
"array",
"elements",
".",
"If",
"array",
"is",
"multidimensional",
"array",
"is",
"flattened",
".",
"Returns",
"1",
"if",
"not",
"an",
"array",
"."
] | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/component.py#L171-L180 |
24,842 | SystemRDL/systemrdl-compiler | systemrdl/walker.py | RDLWalker.walk | def walk(self, node, *listeners:RDLListener):
"""
Initiates the walker to traverse the current ``node`` and its children.
Calls the corresponding callback for each of the ``listeners`` provided in
the order that they are listed.
Parameters
----------
node : :class:`~systemrdl.node.Node`
Node to start traversing.
Listener traversal includes this node.
listeners : list
List of :class:`~RDLListener` that are invoked during
node traversal.
Listener callbacks are executed in the same order as provided by this
parameter.
"""
for listener in listeners:
self.do_enter(node, listener)
for child in node.children(unroll=self.unroll, skip_not_present=self.skip_not_present):
self.walk(child, *listeners)
for listener in listeners:
self.do_exit(node, listener) | python | def walk(self, node, *listeners:RDLListener):
for listener in listeners:
self.do_enter(node, listener)
for child in node.children(unroll=self.unroll, skip_not_present=self.skip_not_present):
self.walk(child, *listeners)
for listener in listeners:
self.do_exit(node, listener) | [
"def",
"walk",
"(",
"self",
",",
"node",
",",
"*",
"listeners",
":",
"RDLListener",
")",
":",
"for",
"listener",
"in",
"listeners",
":",
"self",
".",
"do_enter",
"(",
"node",
",",
"listener",
")",
"for",
"child",
"in",
"node",
".",
"children",
"(",
"... | Initiates the walker to traverse the current ``node`` and its children.
Calls the corresponding callback for each of the ``listeners`` provided in
the order that they are listed.
Parameters
----------
node : :class:`~systemrdl.node.Node`
Node to start traversing.
Listener traversal includes this node.
listeners : list
List of :class:`~RDLListener` that are invoked during
node traversal.
Listener callbacks are executed in the same order as provided by this
parameter. | [
"Initiates",
"the",
"walker",
"to",
"traverse",
"the",
"current",
"node",
"and",
"its",
"children",
".",
"Calls",
"the",
"corresponding",
"callback",
"for",
"each",
"of",
"the",
"listeners",
"provided",
"in",
"the",
"order",
"that",
"they",
"are",
"listed",
... | 6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/walker.py#L99-L124 |
24,843 | elmotec/massedit | massedit.py | get_function | def get_function(fn_name):
"""Retrieve the function defined by the function_name.
Arguments:
fn_name: specification of the type module:function_name.
"""
module_name, callable_name = fn_name.split(':')
current = globals()
if not callable_name:
callable_name = module_name
else:
import importlib
try:
module = importlib.import_module(module_name)
except ImportError:
log.error("failed to import %s", module_name)
raise
current = module
for level in callable_name.split('.'):
current = getattr(current, level)
code = current.__code__
if code.co_argcount != 2:
raise ValueError('function should take 2 arguments: lines, file_name')
return current | python | def get_function(fn_name):
module_name, callable_name = fn_name.split(':')
current = globals()
if not callable_name:
callable_name = module_name
else:
import importlib
try:
module = importlib.import_module(module_name)
except ImportError:
log.error("failed to import %s", module_name)
raise
current = module
for level in callable_name.split('.'):
current = getattr(current, level)
code = current.__code__
if code.co_argcount != 2:
raise ValueError('function should take 2 arguments: lines, file_name')
return current | [
"def",
"get_function",
"(",
"fn_name",
")",
":",
"module_name",
",",
"callable_name",
"=",
"fn_name",
".",
"split",
"(",
"':'",
")",
"current",
"=",
"globals",
"(",
")",
"if",
"not",
"callable_name",
":",
"callable_name",
"=",
"module_name",
"else",
":",
"... | Retrieve the function defined by the function_name.
Arguments:
fn_name: specification of the type module:function_name. | [
"Retrieve",
"the",
"function",
"defined",
"by",
"the",
"function_name",
"."
] | 57e22787354896d63a8850312314b19aa0308906 | https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L66-L90 |
24,844 | elmotec/massedit | massedit.py | parse_command_line | def parse_command_line(argv):
"""Parse command line argument. See -h option.
Arguments:
argv: arguments on the command line must include caller file name.
"""
import textwrap
example = textwrap.dedent("""
Examples:
# Simple string substitution (-e). Will show a diff. No changes applied.
{0} -e "re.sub('failIf', 'assertFalse', line)" *.py
# File level modifications (-f). Overwrites the files in place (-w).
{0} -w -f fixer:fixit *.py
# Will change all test*.py in subdirectories of tests.
{0} -e "re.sub('failIf', 'assertFalse', line)" -s tests test*.py
""").format(os.path.basename(argv[0]))
formatter_class = argparse.RawDescriptionHelpFormatter
parser = argparse.ArgumentParser(description="Python mass editor",
epilog=example,
formatter_class=formatter_class)
parser.add_argument("-V", "--version", action="version",
version="%(prog)s {}".format(__version__))
parser.add_argument("-w", "--write", dest="dry_run",
action="store_false", default=True,
help="modify target file(s) in place. "
"Shows diff otherwise.")
parser.add_argument("-v", "--verbose", dest="verbose_count",
action="count", default=0,
help="increases log verbosity (can be specified "
"multiple times)")
parser.add_argument("-e", "--expression", dest="expressions", nargs=1,
help="Python expressions applied to target files. "
"Use the line variable to reference the current line.")
parser.add_argument("-f", "--function", dest="functions", nargs=1,
help="Python function to apply to target file. "
"Takes file content as input and yield lines. "
"Specify function as [module]:?<function name>.")
parser.add_argument("-x", "--executable", dest="executables", nargs=1,
help="Python executable to apply to target file.")
parser.add_argument("-s", "--start", dest="start_dirs",
help="Directory(ies) from which to look for targets.")
parser.add_argument("-m", "--max-depth-level", type=int, dest="max_depth",
help="Maximum depth when walking subdirectories.")
parser.add_argument("-o", "--output", metavar="FILE",
type=argparse.FileType("w"), default=sys.stdout,
help="redirect output to a file")
parser.add_argument("-g", "--generate", metavar="FILE", type=str,
help="generate input file suitable for -f option")
parser.add_argument("--encoding", dest="encoding",
help="Encoding of input and output files")
parser.add_argument("--newline", dest="newline",
help="Newline character for output files")
parser.add_argument("patterns", metavar="pattern",
nargs="*", # argparse.REMAINDER,
help="shell-like file name patterns to process.")
arguments = parser.parse_args(argv[1:])
if not (arguments.expressions or
arguments.functions or
arguments.generate or
arguments.executables):
parser.error(
'--expression, --function, --generate or --executable missing')
# Sets log level to WARN going more verbose for each new -V.
log.setLevel(max(3 - arguments.verbose_count, 0) * 10)
return arguments | python | def parse_command_line(argv):
import textwrap
example = textwrap.dedent("""
Examples:
# Simple string substitution (-e). Will show a diff. No changes applied.
{0} -e "re.sub('failIf', 'assertFalse', line)" *.py
# File level modifications (-f). Overwrites the files in place (-w).
{0} -w -f fixer:fixit *.py
# Will change all test*.py in subdirectories of tests.
{0} -e "re.sub('failIf', 'assertFalse', line)" -s tests test*.py
""").format(os.path.basename(argv[0]))
formatter_class = argparse.RawDescriptionHelpFormatter
parser = argparse.ArgumentParser(description="Python mass editor",
epilog=example,
formatter_class=formatter_class)
parser.add_argument("-V", "--version", action="version",
version="%(prog)s {}".format(__version__))
parser.add_argument("-w", "--write", dest="dry_run",
action="store_false", default=True,
help="modify target file(s) in place. "
"Shows diff otherwise.")
parser.add_argument("-v", "--verbose", dest="verbose_count",
action="count", default=0,
help="increases log verbosity (can be specified "
"multiple times)")
parser.add_argument("-e", "--expression", dest="expressions", nargs=1,
help="Python expressions applied to target files. "
"Use the line variable to reference the current line.")
parser.add_argument("-f", "--function", dest="functions", nargs=1,
help="Python function to apply to target file. "
"Takes file content as input and yield lines. "
"Specify function as [module]:?<function name>.")
parser.add_argument("-x", "--executable", dest="executables", nargs=1,
help="Python executable to apply to target file.")
parser.add_argument("-s", "--start", dest="start_dirs",
help="Directory(ies) from which to look for targets.")
parser.add_argument("-m", "--max-depth-level", type=int, dest="max_depth",
help="Maximum depth when walking subdirectories.")
parser.add_argument("-o", "--output", metavar="FILE",
type=argparse.FileType("w"), default=sys.stdout,
help="redirect output to a file")
parser.add_argument("-g", "--generate", metavar="FILE", type=str,
help="generate input file suitable for -f option")
parser.add_argument("--encoding", dest="encoding",
help="Encoding of input and output files")
parser.add_argument("--newline", dest="newline",
help="Newline character for output files")
parser.add_argument("patterns", metavar="pattern",
nargs="*", # argparse.REMAINDER,
help="shell-like file name patterns to process.")
arguments = parser.parse_args(argv[1:])
if not (arguments.expressions or
arguments.functions or
arguments.generate or
arguments.executables):
parser.error(
'--expression, --function, --generate or --executable missing')
# Sets log level to WARN going more verbose for each new -V.
log.setLevel(max(3 - arguments.verbose_count, 0) * 10)
return arguments | [
"def",
"parse_command_line",
"(",
"argv",
")",
":",
"import",
"textwrap",
"example",
"=",
"textwrap",
".",
"dedent",
"(",
"\"\"\"\n Examples:\n # Simple string substitution (-e). Will show a diff. No changes applied.\n {0} -e \"re.sub('failIf', 'assertFalse', line)\" *.py\n\n ... | Parse command line argument. See -h option.
Arguments:
argv: arguments on the command line must include caller file name. | [
"Parse",
"command",
"line",
"argument",
".",
"See",
"-",
"h",
"option",
"."
] | 57e22787354896d63a8850312314b19aa0308906 | https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L332-L402 |
24,845 | elmotec/massedit | massedit.py | get_paths | def get_paths(patterns, start_dirs=None, max_depth=1):
"""Retrieve files that match any of the patterns."""
# Shortcut: if there is only one pattern, make sure we process just that.
if len(patterns) == 1 and not start_dirs:
pattern = patterns[0]
directory = os.path.dirname(pattern)
if directory:
patterns = [os.path.basename(pattern)]
start_dirs = directory
max_depth = 1
if not start_dirs or start_dirs == '.':
start_dirs = os.getcwd()
for start_dir in start_dirs.split(','):
for root, dirs, files in os.walk(start_dir): # pylint: disable=W0612
if max_depth is not None:
relpath = os.path.relpath(root, start=start_dir)
depth = len(relpath.split(os.sep))
if depth > max_depth:
continue
names = []
for pattern in patterns:
names += fnmatch.filter(files, pattern)
for name in names:
path = os.path.join(root, name)
yield path | python | def get_paths(patterns, start_dirs=None, max_depth=1):
# Shortcut: if there is only one pattern, make sure we process just that.
if len(patterns) == 1 and not start_dirs:
pattern = patterns[0]
directory = os.path.dirname(pattern)
if directory:
patterns = [os.path.basename(pattern)]
start_dirs = directory
max_depth = 1
if not start_dirs or start_dirs == '.':
start_dirs = os.getcwd()
for start_dir in start_dirs.split(','):
for root, dirs, files in os.walk(start_dir): # pylint: disable=W0612
if max_depth is not None:
relpath = os.path.relpath(root, start=start_dir)
depth = len(relpath.split(os.sep))
if depth > max_depth:
continue
names = []
for pattern in patterns:
names += fnmatch.filter(files, pattern)
for name in names:
path = os.path.join(root, name)
yield path | [
"def",
"get_paths",
"(",
"patterns",
",",
"start_dirs",
"=",
"None",
",",
"max_depth",
"=",
"1",
")",
":",
"# Shortcut: if there is only one pattern, make sure we process just that.",
"if",
"len",
"(",
"patterns",
")",
"==",
"1",
"and",
"not",
"start_dirs",
":",
"... | Retrieve files that match any of the patterns. | [
"Retrieve",
"files",
"that",
"match",
"any",
"of",
"the",
"patterns",
"."
] | 57e22787354896d63a8850312314b19aa0308906 | https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L405-L430 |
24,846 | elmotec/massedit | massedit.py | edit_files | def edit_files(patterns, expressions=None,
functions=None, executables=None,
start_dirs=None, max_depth=1, dry_run=True,
output=sys.stdout, encoding=None, newline=None):
"""Process patterns with MassEdit.
Arguments:
patterns: file pattern to identify the files to be processed.
expressions: single python expression to be applied line by line.
functions: functions to process files contents.
executables: os executables to execute on the argument files.
Keyword arguments:
max_depth: maximum recursion level when looking for file matches.
start_dirs: workspace(ies) where to start the file search.
dry_run: only display differences if True. Save modified file otherwise.
output: handle where the output should be redirected.
Return:
list of files processed.
"""
if not is_list(patterns):
raise TypeError("patterns should be a list")
if expressions and not is_list(expressions):
raise TypeError("expressions should be a list of exec expressions")
if functions and not is_list(functions):
raise TypeError("functions should be a list of functions")
if executables and not is_list(executables):
raise TypeError("executables should be a list of program names")
editor = MassEdit(dry_run=dry_run, encoding=encoding, newline=newline)
if expressions:
editor.set_code_exprs(expressions)
if functions:
editor.set_functions(functions)
if executables:
editor.set_executables(executables)
processed_paths = []
for path in get_paths(patterns, start_dirs=start_dirs,
max_depth=max_depth):
try:
diffs = list(editor.edit_file(path))
if dry_run:
# At this point, encoding is the input encoding.
diff = "".join(diffs)
if not diff:
continue
# The encoding of the target output may not match the input
# encoding. If it's defined, we round trip the diff text
# to bytes and back to silence any conversion errors.
encoding = output.encoding
if encoding:
bytes_diff = diff.encode(encoding=encoding, errors='ignore')
diff = bytes_diff.decode(encoding=output.encoding)
output.write(diff)
except UnicodeDecodeError as err:
log.error("failed to process %s: %s", path, err)
continue
processed_paths.append(os.path.abspath(path))
return processed_paths | python | def edit_files(patterns, expressions=None,
functions=None, executables=None,
start_dirs=None, max_depth=1, dry_run=True,
output=sys.stdout, encoding=None, newline=None):
if not is_list(patterns):
raise TypeError("patterns should be a list")
if expressions and not is_list(expressions):
raise TypeError("expressions should be a list of exec expressions")
if functions and not is_list(functions):
raise TypeError("functions should be a list of functions")
if executables and not is_list(executables):
raise TypeError("executables should be a list of program names")
editor = MassEdit(dry_run=dry_run, encoding=encoding, newline=newline)
if expressions:
editor.set_code_exprs(expressions)
if functions:
editor.set_functions(functions)
if executables:
editor.set_executables(executables)
processed_paths = []
for path in get_paths(patterns, start_dirs=start_dirs,
max_depth=max_depth):
try:
diffs = list(editor.edit_file(path))
if dry_run:
# At this point, encoding is the input encoding.
diff = "".join(diffs)
if not diff:
continue
# The encoding of the target output may not match the input
# encoding. If it's defined, we round trip the diff text
# to bytes and back to silence any conversion errors.
encoding = output.encoding
if encoding:
bytes_diff = diff.encode(encoding=encoding, errors='ignore')
diff = bytes_diff.decode(encoding=output.encoding)
output.write(diff)
except UnicodeDecodeError as err:
log.error("failed to process %s: %s", path, err)
continue
processed_paths.append(os.path.abspath(path))
return processed_paths | [
"def",
"edit_files",
"(",
"patterns",
",",
"expressions",
"=",
"None",
",",
"functions",
"=",
"None",
",",
"executables",
"=",
"None",
",",
"start_dirs",
"=",
"None",
",",
"max_depth",
"=",
"1",
",",
"dry_run",
"=",
"True",
",",
"output",
"=",
"sys",
"... | Process patterns with MassEdit.
Arguments:
patterns: file pattern to identify the files to be processed.
expressions: single python expression to be applied line by line.
functions: functions to process files contents.
executables: os executables to execute on the argument files.
Keyword arguments:
max_depth: maximum recursion level when looking for file matches.
start_dirs: workspace(ies) where to start the file search.
dry_run: only display differences if True. Save modified file otherwise.
output: handle where the output should be redirected.
Return:
list of files processed. | [
"Process",
"patterns",
"with",
"MassEdit",
"."
] | 57e22787354896d63a8850312314b19aa0308906 | https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L469-L530 |
24,847 | elmotec/massedit | massedit.py | command_line | def command_line(argv):
"""Instantiate an editor and process arguments.
Optional argument:
- processed_paths: paths processed are appended to the list.
"""
arguments = parse_command_line(argv)
if arguments.generate:
generate_fixer_file(arguments.generate)
paths = edit_files(arguments.patterns,
expressions=arguments.expressions,
functions=arguments.functions,
executables=arguments.executables,
start_dirs=arguments.start_dirs,
max_depth=arguments.max_depth,
dry_run=arguments.dry_run,
output=arguments.output,
encoding=arguments.encoding,
newline=arguments.newline)
# If the output is not sys.stdout, we need to close it because
# argparse.FileType does not do it for us.
is_sys = arguments.output in [sys.stdout, sys.stderr]
if not is_sys and isinstance(arguments.output, io.IOBase):
arguments.output.close()
return paths | python | def command_line(argv):
arguments = parse_command_line(argv)
if arguments.generate:
generate_fixer_file(arguments.generate)
paths = edit_files(arguments.patterns,
expressions=arguments.expressions,
functions=arguments.functions,
executables=arguments.executables,
start_dirs=arguments.start_dirs,
max_depth=arguments.max_depth,
dry_run=arguments.dry_run,
output=arguments.output,
encoding=arguments.encoding,
newline=arguments.newline)
# If the output is not sys.stdout, we need to close it because
# argparse.FileType does not do it for us.
is_sys = arguments.output in [sys.stdout, sys.stderr]
if not is_sys and isinstance(arguments.output, io.IOBase):
arguments.output.close()
return paths | [
"def",
"command_line",
"(",
"argv",
")",
":",
"arguments",
"=",
"parse_command_line",
"(",
"argv",
")",
"if",
"arguments",
".",
"generate",
":",
"generate_fixer_file",
"(",
"arguments",
".",
"generate",
")",
"paths",
"=",
"edit_files",
"(",
"arguments",
".",
... | Instantiate an editor and process arguments.
Optional argument:
- processed_paths: paths processed are appended to the list. | [
"Instantiate",
"an",
"editor",
"and",
"process",
"arguments",
"."
] | 57e22787354896d63a8850312314b19aa0308906 | https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L533-L558 |
24,848 | elmotec/massedit | massedit.py | MassEdit.import_module | def import_module(module): # pylint: disable=R0201
"""Import module that are needed for the code expr to compile.
Argument:
module (str or list): module(s) to import.
"""
if isinstance(module, list):
all_modules = module
else:
all_modules = [module]
for mod in all_modules:
globals()[mod] = __import__(mod.strip()) | python | def import_module(module): # pylint: disable=R0201
if isinstance(module, list):
all_modules = module
else:
all_modules = [module]
for mod in all_modules:
globals()[mod] = __import__(mod.strip()) | [
"def",
"import_module",
"(",
"module",
")",
":",
"# pylint: disable=R0201",
"if",
"isinstance",
"(",
"module",
",",
"list",
")",
":",
"all_modules",
"=",
"module",
"else",
":",
"all_modules",
"=",
"[",
"module",
"]",
"for",
"mod",
"in",
"all_modules",
":",
... | Import module that are needed for the code expr to compile.
Argument:
module (str or list): module(s) to import. | [
"Import",
"module",
"that",
"are",
"needed",
"for",
"the",
"code",
"expr",
"to",
"compile",
"."
] | 57e22787354896d63a8850312314b19aa0308906 | https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L131-L143 |
24,849 | elmotec/massedit | massedit.py | MassEdit.__edit_line | def __edit_line(line, code, code_obj): # pylint: disable=R0201
"""Edit a line with one code object built in the ctor."""
try:
# pylint: disable=eval-used
result = eval(code_obj, globals(), locals())
except TypeError as ex:
log.error("failed to execute %s: %s", code, ex)
raise
if result is None:
log.error("cannot process line '%s' with %s", line, code)
raise RuntimeError('failed to process line')
elif isinstance(result, list) or isinstance(result, tuple):
line = unicode(' '.join([unicode(res_element)
for res_element in result]))
else:
line = unicode(result)
return line | python | def __edit_line(line, code, code_obj): # pylint: disable=R0201
try:
# pylint: disable=eval-used
result = eval(code_obj, globals(), locals())
except TypeError as ex:
log.error("failed to execute %s: %s", code, ex)
raise
if result is None:
log.error("cannot process line '%s' with %s", line, code)
raise RuntimeError('failed to process line')
elif isinstance(result, list) or isinstance(result, tuple):
line = unicode(' '.join([unicode(res_element)
for res_element in result]))
else:
line = unicode(result)
return line | [
"def",
"__edit_line",
"(",
"line",
",",
"code",
",",
"code_obj",
")",
":",
"# pylint: disable=R0201",
"try",
":",
"# pylint: disable=eval-used",
"result",
"=",
"eval",
"(",
"code_obj",
",",
"globals",
"(",
")",
",",
"locals",
"(",
")",
")",
"except",
"TypeEr... | Edit a line with one code object built in the ctor. | [
"Edit",
"a",
"line",
"with",
"one",
"code",
"object",
"built",
"in",
"the",
"ctor",
"."
] | 57e22787354896d63a8850312314b19aa0308906 | https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L146-L162 |
24,850 | elmotec/massedit | massedit.py | MassEdit.edit_line | def edit_line(self, line):
"""Edit a single line using the code expression."""
for code, code_obj in self.code_objs.items():
line = self.__edit_line(line, code, code_obj)
return line | python | def edit_line(self, line):
for code, code_obj in self.code_objs.items():
line = self.__edit_line(line, code, code_obj)
return line | [
"def",
"edit_line",
"(",
"self",
",",
"line",
")",
":",
"for",
"code",
",",
"code_obj",
"in",
"self",
".",
"code_objs",
".",
"items",
"(",
")",
":",
"line",
"=",
"self",
".",
"__edit_line",
"(",
"line",
",",
"code",
",",
"code_obj",
")",
"return",
... | Edit a single line using the code expression. | [
"Edit",
"a",
"single",
"line",
"using",
"the",
"code",
"expression",
"."
] | 57e22787354896d63a8850312314b19aa0308906 | https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L164-L168 |
24,851 | elmotec/massedit | massedit.py | MassEdit.edit_content | def edit_content(self, original_lines, file_name):
"""Processes a file contents.
First processes the contents line by line applying the registered
expressions, then process the resulting contents using the
registered functions.
Arguments:
original_lines (list of str): file content.
file_name (str): name of the file.
"""
lines = [self.edit_line(line) for line in original_lines]
for function in self._functions:
try:
lines = list(function(lines, file_name))
except UnicodeDecodeError as err:
log.error('failed to process %s: %s', file_name, err)
return lines
except Exception as err:
log.error("failed to process %s with code %s: %s",
file_name, function, err)
raise # Let the exception be handled at a higher level.
return lines | python | def edit_content(self, original_lines, file_name):
lines = [self.edit_line(line) for line in original_lines]
for function in self._functions:
try:
lines = list(function(lines, file_name))
except UnicodeDecodeError as err:
log.error('failed to process %s: %s', file_name, err)
return lines
except Exception as err:
log.error("failed to process %s with code %s: %s",
file_name, function, err)
raise # Let the exception be handled at a higher level.
return lines | [
"def",
"edit_content",
"(",
"self",
",",
"original_lines",
",",
"file_name",
")",
":",
"lines",
"=",
"[",
"self",
".",
"edit_line",
"(",
"line",
")",
"for",
"line",
"in",
"original_lines",
"]",
"for",
"function",
"in",
"self",
".",
"_functions",
":",
"tr... | Processes a file contents.
First processes the contents line by line applying the registered
expressions, then process the resulting contents using the
registered functions.
Arguments:
original_lines (list of str): file content.
file_name (str): name of the file. | [
"Processes",
"a",
"file",
"contents",
"."
] | 57e22787354896d63a8850312314b19aa0308906 | https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L170-L193 |
24,852 | elmotec/massedit | massedit.py | MassEdit.append_code_expr | def append_code_expr(self, code):
"""Compile argument and adds it to the list of code objects."""
# expects a string.
if isinstance(code, str) and not isinstance(code, unicode):
code = unicode(code)
if not isinstance(code, unicode):
raise TypeError("string expected")
log.debug("compiling code %s...", code)
try:
code_obj = compile(code, '<string>', 'eval')
self.code_objs[code] = code_obj
except SyntaxError as syntax_err:
log.error("cannot compile %s: %s", code, syntax_err)
raise
log.debug("compiled code %s", code) | python | def append_code_expr(self, code):
# expects a string.
if isinstance(code, str) and not isinstance(code, unicode):
code = unicode(code)
if not isinstance(code, unicode):
raise TypeError("string expected")
log.debug("compiling code %s...", code)
try:
code_obj = compile(code, '<string>', 'eval')
self.code_objs[code] = code_obj
except SyntaxError as syntax_err:
log.error("cannot compile %s: %s", code, syntax_err)
raise
log.debug("compiled code %s", code) | [
"def",
"append_code_expr",
"(",
"self",
",",
"code",
")",
":",
"# expects a string.",
"if",
"isinstance",
"(",
"code",
",",
"str",
")",
"and",
"not",
"isinstance",
"(",
"code",
",",
"unicode",
")",
":",
"code",
"=",
"unicode",
"(",
"code",
")",
"if",
"... | Compile argument and adds it to the list of code objects. | [
"Compile",
"argument",
"and",
"adds",
"it",
"to",
"the",
"list",
"of",
"code",
"objects",
"."
] | 57e22787354896d63a8850312314b19aa0308906 | https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L262-L276 |
24,853 | elmotec/massedit | massedit.py | MassEdit.append_function | def append_function(self, function):
"""Append the function to the list of functions to be called.
If the function is already a callable, use it. If it's a type str
try to interpret it as [module]:?<callable>, load the module
if there is one and retrieve the callable.
Argument:
function (str or callable): function to call on input.
"""
if not hasattr(function, '__call__'):
function = get_function(function)
if not hasattr(function, '__call__'):
raise ValueError("function is expected to be callable")
self._functions.append(function)
log.debug("registered %s", function.__name__) | python | def append_function(self, function):
if not hasattr(function, '__call__'):
function = get_function(function)
if not hasattr(function, '__call__'):
raise ValueError("function is expected to be callable")
self._functions.append(function)
log.debug("registered %s", function.__name__) | [
"def",
"append_function",
"(",
"self",
",",
"function",
")",
":",
"if",
"not",
"hasattr",
"(",
"function",
",",
"'__call__'",
")",
":",
"function",
"=",
"get_function",
"(",
"function",
")",
"if",
"not",
"hasattr",
"(",
"function",
",",
"'__call__'",
")",
... | Append the function to the list of functions to be called.
If the function is already a callable, use it. If it's a type str
try to interpret it as [module]:?<callable>, load the module
if there is one and retrieve the callable.
Argument:
function (str or callable): function to call on input. | [
"Append",
"the",
"function",
"to",
"the",
"list",
"of",
"functions",
"to",
"be",
"called",
"."
] | 57e22787354896d63a8850312314b19aa0308906 | https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L278-L294 |
24,854 | elmotec/massedit | massedit.py | MassEdit.append_executable | def append_executable(self, executable):
"""Append san executable os command to the list to be called.
Argument:
executable (str): os callable executable.
"""
if isinstance(executable, str) and not isinstance(executable, unicode):
executable = unicode(executable)
if not isinstance(executable, unicode):
raise TypeError("expected executable name as str, not {}".
format(executable.__class__.__name__))
self._executables.append(executable) | python | def append_executable(self, executable):
if isinstance(executable, str) and not isinstance(executable, unicode):
executable = unicode(executable)
if not isinstance(executable, unicode):
raise TypeError("expected executable name as str, not {}".
format(executable.__class__.__name__))
self._executables.append(executable) | [
"def",
"append_executable",
"(",
"self",
",",
"executable",
")",
":",
"if",
"isinstance",
"(",
"executable",
",",
"str",
")",
"and",
"not",
"isinstance",
"(",
"executable",
",",
"unicode",
")",
":",
"executable",
"=",
"unicode",
"(",
"executable",
")",
"if... | Append san executable os command to the list to be called.
Argument:
executable (str): os callable executable. | [
"Append",
"san",
"executable",
"os",
"command",
"to",
"the",
"list",
"to",
"be",
"called",
"."
] | 57e22787354896d63a8850312314b19aa0308906 | https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L296-L308 |
24,855 | elmotec/massedit | massedit.py | MassEdit.set_functions | def set_functions(self, functions):
"""Check functions passed as argument and set them to be used."""
for func in functions:
try:
self.append_function(func)
except (ValueError, AttributeError) as ex:
log.error("'%s' is not a callable function: %s", func, ex)
raise | python | def set_functions(self, functions):
for func in functions:
try:
self.append_function(func)
except (ValueError, AttributeError) as ex:
log.error("'%s' is not a callable function: %s", func, ex)
raise | [
"def",
"set_functions",
"(",
"self",
",",
"functions",
")",
":",
"for",
"func",
"in",
"functions",
":",
"try",
":",
"self",
".",
"append_function",
"(",
"func",
")",
"except",
"(",
"ValueError",
",",
"AttributeError",
")",
"as",
"ex",
":",
"log",
".",
... | Check functions passed as argument and set them to be used. | [
"Check",
"functions",
"passed",
"as",
"argument",
"and",
"set",
"them",
"to",
"be",
"used",
"."
] | 57e22787354896d63a8850312314b19aa0308906 | https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L317-L324 |
24,856 | wonambi-python/wonambi | wonambi/ioeeg/mnefiff.py | write_mnefiff | def write_mnefiff(data, filename):
"""Export data to MNE using FIFF format.
Parameters
----------
data : instance of ChanTime
data with only one trial
filename : path to file
file to export to (include '.mat')
Notes
-----
It cannot store data larger than 2 GB.
The data is assumed to have only EEG electrodes.
It overwrites a file if it exists.
"""
from mne import create_info, set_log_level
from mne.io import RawArray
set_log_level(WARNING)
TRIAL = 0
info = create_info(list(data.axis['chan'][TRIAL]), data.s_freq, ['eeg', ] *
data.number_of('chan')[TRIAL])
UNITS = 1e-6 # mne wants data in uV
fiff = RawArray(data.data[0] * UNITS, info)
if data.attr['chan']:
fiff.set_channel_positions(data.attr['chan'].return_xyz(),
data.attr['chan'].return_label())
fiff.save(filename, overwrite=True) | python | def write_mnefiff(data, filename):
from mne import create_info, set_log_level
from mne.io import RawArray
set_log_level(WARNING)
TRIAL = 0
info = create_info(list(data.axis['chan'][TRIAL]), data.s_freq, ['eeg', ] *
data.number_of('chan')[TRIAL])
UNITS = 1e-6 # mne wants data in uV
fiff = RawArray(data.data[0] * UNITS, info)
if data.attr['chan']:
fiff.set_channel_positions(data.attr['chan'].return_xyz(),
data.attr['chan'].return_label())
fiff.save(filename, overwrite=True) | [
"def",
"write_mnefiff",
"(",
"data",
",",
"filename",
")",
":",
"from",
"mne",
"import",
"create_info",
",",
"set_log_level",
"from",
"mne",
".",
"io",
"import",
"RawArray",
"set_log_level",
"(",
"WARNING",
")",
"TRIAL",
"=",
"0",
"info",
"=",
"create_info",... | Export data to MNE using FIFF format.
Parameters
----------
data : instance of ChanTime
data with only one trial
filename : path to file
file to export to (include '.mat')
Notes
-----
It cannot store data larger than 2 GB.
The data is assumed to have only EEG electrodes.
It overwrites a file if it exists. | [
"Export",
"data",
"to",
"MNE",
"using",
"FIFF",
"format",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/mnefiff.py#L5-L37 |
24,857 | wonambi-python/wonambi | wonambi/detect/spindle.py | detect_UCSD | def detect_UCSD(dat_orig, s_freq, time, opts):
"""Spindle detection based on the UCSD method
Parameters
----------
dat_orig : ndarray (dtype='float')
vector with the data for one channel
s_freq : float
sampling frequency
time : ndarray (dtype='float')
vector with the time points for each sample
opts : instance of 'DetectSpindle'
det_wavelet : dict
parameters for 'wavelet_real',
det_thres' : float
detection threshold
sel_thresh : float
selection threshold
duration : tuple of float
min and max duration of spindles
frequency : tuple of float
low and high frequency of spindle band (for power ratio)
ratio_thresh : float
ratio between power inside and outside spindle band to accept them
Returns
-------
list of dict
list of detected spindles
dict
'det_value_lo' with detection value, 'det_value_hi' with nan,
'sel_value' with selection value
float
spindle density, per 30-s epoch
"""
dat_det = transform_signal(dat_orig, s_freq, 'wavelet_real',
opts.det_wavelet)
det_value = define_threshold(dat_det, s_freq, 'median+std',
opts.det_thresh)
events = detect_events(dat_det, 'maxima', det_value)
dat_sel = transform_signal(dat_orig, s_freq, 'wavelet_real',
opts.sel_wavelet)
sel_value = define_threshold(dat_sel, s_freq, 'median+std',
opts.sel_thresh)
events = select_events(dat_sel, events, 'above_thresh', sel_value)
events = _merge_close(dat_det, events, time, opts.tolerance)
events = within_duration(events, time, opts.duration)
events = _merge_close(dat_det, events, time, opts.min_interval)
events = remove_straddlers(events, time, s_freq)
events = power_ratio(events, dat_orig, s_freq, opts.frequency,
opts.ratio_thresh)
power_peaks = peak_in_power(events, dat_orig, s_freq, opts.power_peaks)
powers = power_in_band(events, dat_orig, s_freq, opts.frequency)
sp_in_chan = make_spindles(events, power_peaks, powers, dat_det,
dat_orig, time, s_freq)
values = {'det_value_lo': det_value, 'sel_value': sel_value}
density = len(sp_in_chan) * s_freq * 30 / len(dat_orig)
return sp_in_chan, values, density | python | def detect_UCSD(dat_orig, s_freq, time, opts):
dat_det = transform_signal(dat_orig, s_freq, 'wavelet_real',
opts.det_wavelet)
det_value = define_threshold(dat_det, s_freq, 'median+std',
opts.det_thresh)
events = detect_events(dat_det, 'maxima', det_value)
dat_sel = transform_signal(dat_orig, s_freq, 'wavelet_real',
opts.sel_wavelet)
sel_value = define_threshold(dat_sel, s_freq, 'median+std',
opts.sel_thresh)
events = select_events(dat_sel, events, 'above_thresh', sel_value)
events = _merge_close(dat_det, events, time, opts.tolerance)
events = within_duration(events, time, opts.duration)
events = _merge_close(dat_det, events, time, opts.min_interval)
events = remove_straddlers(events, time, s_freq)
events = power_ratio(events, dat_orig, s_freq, opts.frequency,
opts.ratio_thresh)
power_peaks = peak_in_power(events, dat_orig, s_freq, opts.power_peaks)
powers = power_in_band(events, dat_orig, s_freq, opts.frequency)
sp_in_chan = make_spindles(events, power_peaks, powers, dat_det,
dat_orig, time, s_freq)
values = {'det_value_lo': det_value, 'sel_value': sel_value}
density = len(sp_in_chan) * s_freq * 30 / len(dat_orig)
return sp_in_chan, values, density | [
"def",
"detect_UCSD",
"(",
"dat_orig",
",",
"s_freq",
",",
"time",
",",
"opts",
")",
":",
"dat_det",
"=",
"transform_signal",
"(",
"dat_orig",
",",
"s_freq",
",",
"'wavelet_real'",
",",
"opts",
".",
"det_wavelet",
")",
"det_value",
"=",
"define_threshold",
"... | Spindle detection based on the UCSD method
Parameters
----------
dat_orig : ndarray (dtype='float')
vector with the data for one channel
s_freq : float
sampling frequency
time : ndarray (dtype='float')
vector with the time points for each sample
opts : instance of 'DetectSpindle'
det_wavelet : dict
parameters for 'wavelet_real',
det_thres' : float
detection threshold
sel_thresh : float
selection threshold
duration : tuple of float
min and max duration of spindles
frequency : tuple of float
low and high frequency of spindle band (for power ratio)
ratio_thresh : float
ratio between power inside and outside spindle band to accept them
Returns
-------
list of dict
list of detected spindles
dict
'det_value_lo' with detection value, 'det_value_hi' with nan,
'sel_value' with selection value
float
spindle density, per 30-s epoch | [
"Spindle",
"detection",
"based",
"on",
"the",
"UCSD",
"method"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L984-L1051 |
24,858 | wonambi-python/wonambi | wonambi/detect/spindle.py | detect_Concordia | def detect_Concordia(dat_orig, s_freq, time, opts):
"""Spindle detection, experimental Concordia method. Similar to Moelle 2011
and Nir2011.
Parameters
----------
dat_orig : ndarray (dtype='float')
vector with the data for one channel
s_freq : float
sampling frequency
opts : instance of 'DetectSpindle'
'det_butter' : dict
parameters for 'butter',
'moving_rms' : dict
parameters for 'moving_rms'
'smooth' : dict
parameters for 'smooth'
'det_thresh' : float
low detection threshold
'det_thresh_hi' : float
high detection threshold
'sel_thresh' : float
selection threshold
'duration' : tuple of float
min and max duration of spindles
Returns
-------
list of dict
list of detected spindles
dict
'det_value_lo', 'det_value_hi' with detection values, 'sel_value' with
selection value
float
spindle density, per 30-s epoch
"""
dat_det = transform_signal(dat_orig, s_freq, 'butter', opts.det_butter)
dat_det = transform_signal(dat_det, s_freq, 'moving_rms', opts.moving_rms)
dat_det = transform_signal(dat_det, s_freq, 'smooth', opts.smooth)
det_value_lo = define_threshold(dat_det, s_freq, 'mean+std',
opts.det_thresh)
det_value_hi = define_threshold(dat_det, s_freq, 'mean+std',
opts.det_thresh_hi)
sel_value = define_threshold(dat_det, s_freq, 'mean+std', opts.sel_thresh)
events = detect_events(dat_det, 'between_thresh',
value=(det_value_lo, det_value_hi))
if events is not None:
events = _merge_close(dat_det, events, time, opts.tolerance)
events = select_events(dat_det, events, 'above_thresh', sel_value)
events = within_duration(events, time, opts.duration)
events = _merge_close(dat_det, events, time, opts.min_interval)
events = remove_straddlers(events, time, s_freq)
power_peaks = peak_in_power(events, dat_orig, s_freq, opts.power_peaks)
powers = power_in_band(events, dat_orig, s_freq, opts.frequency)
sp_in_chan = make_spindles(events, power_peaks, powers, dat_det,
dat_orig, time, s_freq)
else:
lg.info('No spindle found')
sp_in_chan = []
values = {'det_value_lo': det_value_lo, 'sel_value': sel_value}
density = len(sp_in_chan) * s_freq * 30 / len(dat_orig)
return sp_in_chan, values, density | python | def detect_Concordia(dat_orig, s_freq, time, opts):
dat_det = transform_signal(dat_orig, s_freq, 'butter', opts.det_butter)
dat_det = transform_signal(dat_det, s_freq, 'moving_rms', opts.moving_rms)
dat_det = transform_signal(dat_det, s_freq, 'smooth', opts.smooth)
det_value_lo = define_threshold(dat_det, s_freq, 'mean+std',
opts.det_thresh)
det_value_hi = define_threshold(dat_det, s_freq, 'mean+std',
opts.det_thresh_hi)
sel_value = define_threshold(dat_det, s_freq, 'mean+std', opts.sel_thresh)
events = detect_events(dat_det, 'between_thresh',
value=(det_value_lo, det_value_hi))
if events is not None:
events = _merge_close(dat_det, events, time, opts.tolerance)
events = select_events(dat_det, events, 'above_thresh', sel_value)
events = within_duration(events, time, opts.duration)
events = _merge_close(dat_det, events, time, opts.min_interval)
events = remove_straddlers(events, time, s_freq)
power_peaks = peak_in_power(events, dat_orig, s_freq, opts.power_peaks)
powers = power_in_band(events, dat_orig, s_freq, opts.frequency)
sp_in_chan = make_spindles(events, power_peaks, powers, dat_det,
dat_orig, time, s_freq)
else:
lg.info('No spindle found')
sp_in_chan = []
values = {'det_value_lo': det_value_lo, 'sel_value': sel_value}
density = len(sp_in_chan) * s_freq * 30 / len(dat_orig)
return sp_in_chan, values, density | [
"def",
"detect_Concordia",
"(",
"dat_orig",
",",
"s_freq",
",",
"time",
",",
"opts",
")",
":",
"dat_det",
"=",
"transform_signal",
"(",
"dat_orig",
",",
"s_freq",
",",
"'butter'",
",",
"opts",
".",
"det_butter",
")",
"dat_det",
"=",
"transform_signal",
"(",
... | Spindle detection, experimental Concordia method. Similar to Moelle 2011
and Nir2011.
Parameters
----------
dat_orig : ndarray (dtype='float')
vector with the data for one channel
s_freq : float
sampling frequency
opts : instance of 'DetectSpindle'
'det_butter' : dict
parameters for 'butter',
'moving_rms' : dict
parameters for 'moving_rms'
'smooth' : dict
parameters for 'smooth'
'det_thresh' : float
low detection threshold
'det_thresh_hi' : float
high detection threshold
'sel_thresh' : float
selection threshold
'duration' : tuple of float
min and max duration of spindles
Returns
-------
list of dict
list of detected spindles
dict
'det_value_lo', 'det_value_hi' with detection values, 'sel_value' with
selection value
float
spindle density, per 30-s epoch | [
"Spindle",
"detection",
"experimental",
"Concordia",
"method",
".",
"Similar",
"to",
"Moelle",
"2011",
"and",
"Nir2011",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1054-L1125 |
24,859 | wonambi-python/wonambi | wonambi/detect/spindle.py | define_threshold | def define_threshold(dat, s_freq, method, value, nbins=120):
"""Return the value of the threshold based on relative values.
Parameters
----------
dat : ndarray (dtype='float')
vector with the data after selection-transformation
s_freq : float
sampling frequency
method : str
one of 'mean', 'median', 'std', 'mean+std', 'median+std', 'histmax'
value : float
value to multiply the values for
nbins : int
for histmax method, number of bins in the histogram
Returns
-------
float
threshold in useful units.
"""
if method == 'mean':
value = value * mean(dat)
elif method == 'median':
value = value * median(dat)
elif method == 'std':
value = value * std(dat)
elif method == 'mean+std':
value = mean(dat) + value * std(dat)
elif method == 'median+std':
value = median(dat) + value * std(dat)
elif method == 'histmax':
hist = histogram(dat, bins=nbins)
idx_maxbin = argmax(hist[0])
maxamp = mean((hist[1][idx_maxbin], hist[1][idx_maxbin + 1]))
value = value * maxamp
return value | python | def define_threshold(dat, s_freq, method, value, nbins=120):
if method == 'mean':
value = value * mean(dat)
elif method == 'median':
value = value * median(dat)
elif method == 'std':
value = value * std(dat)
elif method == 'mean+std':
value = mean(dat) + value * std(dat)
elif method == 'median+std':
value = median(dat) + value * std(dat)
elif method == 'histmax':
hist = histogram(dat, bins=nbins)
idx_maxbin = argmax(hist[0])
maxamp = mean((hist[1][idx_maxbin], hist[1][idx_maxbin + 1]))
value = value * maxamp
return value | [
"def",
"define_threshold",
"(",
"dat",
",",
"s_freq",
",",
"method",
",",
"value",
",",
"nbins",
"=",
"120",
")",
":",
"if",
"method",
"==",
"'mean'",
":",
"value",
"=",
"value",
"*",
"mean",
"(",
"dat",
")",
"elif",
"method",
"==",
"'median'",
":",
... | Return the value of the threshold based on relative values.
Parameters
----------
dat : ndarray (dtype='float')
vector with the data after selection-transformation
s_freq : float
sampling frequency
method : str
one of 'mean', 'median', 'std', 'mean+std', 'median+std', 'histmax'
value : float
value to multiply the values for
nbins : int
for histmax method, number of bins in the histogram
Returns
-------
float
threshold in useful units. | [
"Return",
"the",
"value",
"of",
"the",
"threshold",
"based",
"on",
"relative",
"values",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1483-L1521 |
24,860 | wonambi-python/wonambi | wonambi/detect/spindle.py | detect_events | def detect_events(dat, method, value=None):
"""Detect events using 'above_thresh', 'below_thresh' or
'maxima' method.
Parameters
----------
dat : ndarray (dtype='float')
vector with the data after transformation
method : str
'above_thresh', 'below_thresh' or 'maxima'
value : float or tuple of float
for 'above_thresh' or 'below_thresh', it's the value of threshold for
the event detection
for 'between_thresh', it's the lower and upper threshold as tuple
for 'maxima', it's the distance in s from the peak to find a minimum
Returns
-------
ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
"""
if 'thresh' in method or 'custom' == method:
if method == 'above_thresh':
above_det = dat >= value
detected = _detect_start_end(above_det)
if method == 'below_thresh':
below_det = dat < value
detected = _detect_start_end(below_det)
if method == 'between_thresh':
above_det = dat >= value[0]
below_det = dat < value[1]
between_det = logical_and(above_det, below_det)
detected = _detect_start_end(between_det)
if method == 'custom':
detected = _detect_start_end(dat)
if detected is None:
return None
if method in ['above_thresh', 'custom']:
# add the location of the peak in the middle
detected = insert(detected, 1, 0, axis=1)
for i in detected:
i[1] = i[0] + argmax(dat[i[0]:i[2]])
if method in ['below_thresh', 'between_thresh']:
# add the location of the trough in the middle
detected = insert(detected, 1, 0, axis=1)
for i in detected:
i[1] = i[0] + argmin(dat[i[0]:i[2]])
if method == 'maxima':
peaks = argrelmax(dat)[0]
detected = vstack((peaks, peaks, peaks)).T
if value is not None:
detected = detected[dat[peaks] > value, :]
return detected | python | def detect_events(dat, method, value=None):
if 'thresh' in method or 'custom' == method:
if method == 'above_thresh':
above_det = dat >= value
detected = _detect_start_end(above_det)
if method == 'below_thresh':
below_det = dat < value
detected = _detect_start_end(below_det)
if method == 'between_thresh':
above_det = dat >= value[0]
below_det = dat < value[1]
between_det = logical_and(above_det, below_det)
detected = _detect_start_end(between_det)
if method == 'custom':
detected = _detect_start_end(dat)
if detected is None:
return None
if method in ['above_thresh', 'custom']:
# add the location of the peak in the middle
detected = insert(detected, 1, 0, axis=1)
for i in detected:
i[1] = i[0] + argmax(dat[i[0]:i[2]])
if method in ['below_thresh', 'between_thresh']:
# add the location of the trough in the middle
detected = insert(detected, 1, 0, axis=1)
for i in detected:
i[1] = i[0] + argmin(dat[i[0]:i[2]])
if method == 'maxima':
peaks = argrelmax(dat)[0]
detected = vstack((peaks, peaks, peaks)).T
if value is not None:
detected = detected[dat[peaks] > value, :]
return detected | [
"def",
"detect_events",
"(",
"dat",
",",
"method",
",",
"value",
"=",
"None",
")",
":",
"if",
"'thresh'",
"in",
"method",
"or",
"'custom'",
"==",
"method",
":",
"if",
"method",
"==",
"'above_thresh'",
":",
"above_det",
"=",
"dat",
">=",
"value",
"detecte... | Detect events using 'above_thresh', 'below_thresh' or
'maxima' method.
Parameters
----------
dat : ndarray (dtype='float')
vector with the data after transformation
method : str
'above_thresh', 'below_thresh' or 'maxima'
value : float or tuple of float
for 'above_thresh' or 'below_thresh', it's the value of threshold for
the event detection
for 'between_thresh', it's the lower and upper threshold as tuple
for 'maxima', it's the distance in s from the peak to find a minimum
Returns
-------
ndarray (dtype='int')
N x 3 matrix with start, peak, end samples | [
"Detect",
"events",
"using",
"above_thresh",
"below_thresh",
"or",
"maxima",
"method",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1556-L1619 |
24,861 | wonambi-python/wonambi | wonambi/detect/spindle.py | select_events | def select_events(dat, detected, method, value):
"""Select start sample and end sample of the events.
Parameters
----------
dat : ndarray (dtype='float')
vector with the data after selection-transformation
detected : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
method : str
'above_thresh', 'below_thresh'
value : float
for 'threshold', it's the value of threshold for the spindle selection.
Returns
-------
ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
"""
if method == 'above_thresh':
above_sel = dat >= value
detected = _select_period(detected, above_sel)
elif method == 'below_thresh':
below_sel = dat <= value
detected = _select_period(detected, below_sel)
return detected | python | def select_events(dat, detected, method, value):
if method == 'above_thresh':
above_sel = dat >= value
detected = _select_period(detected, above_sel)
elif method == 'below_thresh':
below_sel = dat <= value
detected = _select_period(detected, below_sel)
return detected | [
"def",
"select_events",
"(",
"dat",
",",
"detected",
",",
"method",
",",
"value",
")",
":",
"if",
"method",
"==",
"'above_thresh'",
":",
"above_sel",
"=",
"dat",
">=",
"value",
"detected",
"=",
"_select_period",
"(",
"detected",
",",
"above_sel",
")",
"eli... | Select start sample and end sample of the events.
Parameters
----------
dat : ndarray (dtype='float')
vector with the data after selection-transformation
detected : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
method : str
'above_thresh', 'below_thresh'
value : float
for 'threshold', it's the value of threshold for the spindle selection.
Returns
-------
ndarray (dtype='int')
N x 3 matrix with start, peak, end samples | [
"Select",
"start",
"sample",
"and",
"end",
"sample",
"of",
"the",
"events",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1622-L1649 |
24,862 | wonambi-python/wonambi | wonambi/detect/spindle.py | merge_close | def merge_close(events, min_interval, merge_to_longer=False):
"""Merge events that are separated by a less than a minimum interval.
Parameters
----------
events : list of dict
events with 'start' and 'end' times, from one or several channels.
**Events must be sorted by their start time.**
min_interval : float
minimum delay between consecutive events, in seconds
merge_to_longer : bool (default: False)
If True, info (chan, peak, etc.) from the longer of the 2 events is
kept. Otherwise, info from the earlier onset spindle is kept.
Returns
-------
list of dict
original events list with close events merged.
"""
half_iv = min_interval / 2
merged = []
for higher in events:
if not merged:
merged.append(higher)
else:
lower = merged[-1]
if higher['start'] - half_iv <= lower['end'] + half_iv:
if merge_to_longer and (higher['end'] - higher['start'] >
lower['end'] - lower['start']):
start = min(lower['start'], higher['start'])
higher.update({'start': start})
merged[-1] = higher
else:
end = max(lower['end'], higher['end'])
merged[-1].update({'end': end})
else:
merged.append(higher)
return merged | python | def merge_close(events, min_interval, merge_to_longer=False):
half_iv = min_interval / 2
merged = []
for higher in events:
if not merged:
merged.append(higher)
else:
lower = merged[-1]
if higher['start'] - half_iv <= lower['end'] + half_iv:
if merge_to_longer and (higher['end'] - higher['start'] >
lower['end'] - lower['start']):
start = min(lower['start'], higher['start'])
higher.update({'start': start})
merged[-1] = higher
else:
end = max(lower['end'], higher['end'])
merged[-1].update({'end': end})
else:
merged.append(higher)
return merged | [
"def",
"merge_close",
"(",
"events",
",",
"min_interval",
",",
"merge_to_longer",
"=",
"False",
")",
":",
"half_iv",
"=",
"min_interval",
"/",
"2",
"merged",
"=",
"[",
"]",
"for",
"higher",
"in",
"events",
":",
"if",
"not",
"merged",
":",
"merged",
".",
... | Merge events that are separated by a less than a minimum interval.
Parameters
----------
events : list of dict
events with 'start' and 'end' times, from one or several channels.
**Events must be sorted by their start time.**
min_interval : float
minimum delay between consecutive events, in seconds
merge_to_longer : bool (default: False)
If True, info (chan, peak, etc.) from the longer of the 2 events is
kept. Otherwise, info from the earlier onset spindle is kept.
Returns
-------
list of dict
original events list with close events merged. | [
"Merge",
"events",
"that",
"are",
"separated",
"by",
"a",
"less",
"than",
"a",
"minimum",
"interval",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1652-L1697 |
24,863 | wonambi-python/wonambi | wonambi/detect/spindle.py | within_duration | def within_duration(events, time, limits):
"""Check whether event is within time limits.
Parameters
----------
events : ndarray (dtype='int')
N x M matrix with start sample first and end samples last on M
time : ndarray (dtype='float')
vector with time points
limits : tuple of float
low and high limit for spindle duration
Returns
-------
ndarray (dtype='int')
N x M matrix with start sample first and end samples last on M
"""
min_dur = max_dur = ones(events.shape[0], dtype=bool)
if limits[0] is not None:
min_dur = time[events[:, -1] - 1] - time[events[:, 0]] >= limits[0]
if limits[1] is not None:
max_dur = time[events[:, -1] - 1] - time[events[:, 0]] <= limits[1]
return events[min_dur & max_dur, :] | python | def within_duration(events, time, limits):
min_dur = max_dur = ones(events.shape[0], dtype=bool)
if limits[0] is not None:
min_dur = time[events[:, -1] - 1] - time[events[:, 0]] >= limits[0]
if limits[1] is not None:
max_dur = time[events[:, -1] - 1] - time[events[:, 0]] <= limits[1]
return events[min_dur & max_dur, :] | [
"def",
"within_duration",
"(",
"events",
",",
"time",
",",
"limits",
")",
":",
"min_dur",
"=",
"max_dur",
"=",
"ones",
"(",
"events",
".",
"shape",
"[",
"0",
"]",
",",
"dtype",
"=",
"bool",
")",
"if",
"limits",
"[",
"0",
"]",
"is",
"not",
"None",
... | Check whether event is within time limits.
Parameters
----------
events : ndarray (dtype='int')
N x M matrix with start sample first and end samples last on M
time : ndarray (dtype='float')
vector with time points
limits : tuple of float
low and high limit for spindle duration
Returns
-------
ndarray (dtype='int')
N x M matrix with start sample first and end samples last on M | [
"Check",
"whether",
"event",
"is",
"within",
"time",
"limits",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1700-L1725 |
24,864 | wonambi-python/wonambi | wonambi/detect/spindle.py | remove_straddlers | def remove_straddlers(events, time, s_freq, toler=0.1):
"""Reject an event if it straddles a stitch, by comparing its
duration to its timespan.
Parameters
----------
events : ndarray (dtype='int')
N x M matrix with start, ..., end samples
time : ndarray (dtype='float')
vector with time points
s_freq : float
sampling frequency
toler : float, def=0.1
maximum tolerated difference between event duration and timespan
Returns
-------
ndarray (dtype='int')
N x M matrix with start , ..., end samples
"""
dur = (events[:, -1] - 1 - events[:, 0]) / s_freq
continuous = time[events[:, -1] - 1] - time[events[:, 0]] - dur < toler
return events[continuous, :] | python | def remove_straddlers(events, time, s_freq, toler=0.1):
dur = (events[:, -1] - 1 - events[:, 0]) / s_freq
continuous = time[events[:, -1] - 1] - time[events[:, 0]] - dur < toler
return events[continuous, :] | [
"def",
"remove_straddlers",
"(",
"events",
",",
"time",
",",
"s_freq",
",",
"toler",
"=",
"0.1",
")",
":",
"dur",
"=",
"(",
"events",
"[",
":",
",",
"-",
"1",
"]",
"-",
"1",
"-",
"events",
"[",
":",
",",
"0",
"]",
")",
"/",
"s_freq",
"continuou... | Reject an event if it straddles a stitch, by comparing its
duration to its timespan.
Parameters
----------
events : ndarray (dtype='int')
N x M matrix with start, ..., end samples
time : ndarray (dtype='float')
vector with time points
s_freq : float
sampling frequency
toler : float, def=0.1
maximum tolerated difference between event duration and timespan
Returns
-------
ndarray (dtype='int')
N x M matrix with start , ..., end samples | [
"Reject",
"an",
"event",
"if",
"it",
"straddles",
"a",
"stitch",
"by",
"comparing",
"its",
"duration",
"to",
"its",
"timespan",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1728-L1751 |
24,865 | wonambi-python/wonambi | wonambi/detect/spindle.py | power_ratio | def power_ratio(events, dat, s_freq, limits, ratio_thresh):
"""Estimate the ratio in power between spindle band and lower frequencies.
Parameters
----------
events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
dat : ndarray (dtype='float')
vector with the original data
s_freq : float
sampling frequency
limits : tuple of float
high and low frequencies for spindle band
ratio_thresh : float
ratio between spindle vs non-spindle amplitude
Returns
-------
ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
Notes
-----
In the original matlab script, it uses amplitude, not power.
"""
ratio = empty(events.shape[0])
for i, one_event in enumerate(events):
x0 = one_event[0]
x1 = one_event[2]
if x0 < 0 or x1 >= len(dat):
ratio[i] = 0
else:
f, Pxx = periodogram(dat[x0:x1], s_freq, scaling='spectrum')
Pxx = sqrt(Pxx) # use amplitude
freq_sp = (f >= limits[0]) & (f <= limits[1])
freq_nonsp = (f <= limits[1])
ratio[i] = mean(Pxx[freq_sp]) / mean(Pxx[freq_nonsp])
events = events[ratio > ratio_thresh, :]
return events | python | def power_ratio(events, dat, s_freq, limits, ratio_thresh):
ratio = empty(events.shape[0])
for i, one_event in enumerate(events):
x0 = one_event[0]
x1 = one_event[2]
if x0 < 0 or x1 >= len(dat):
ratio[i] = 0
else:
f, Pxx = periodogram(dat[x0:x1], s_freq, scaling='spectrum')
Pxx = sqrt(Pxx) # use amplitude
freq_sp = (f >= limits[0]) & (f <= limits[1])
freq_nonsp = (f <= limits[1])
ratio[i] = mean(Pxx[freq_sp]) / mean(Pxx[freq_nonsp])
events = events[ratio > ratio_thresh, :]
return events | [
"def",
"power_ratio",
"(",
"events",
",",
"dat",
",",
"s_freq",
",",
"limits",
",",
"ratio_thresh",
")",
":",
"ratio",
"=",
"empty",
"(",
"events",
".",
"shape",
"[",
"0",
"]",
")",
"for",
"i",
",",
"one_event",
"in",
"enumerate",
"(",
"events",
")",... | Estimate the ratio in power between spindle band and lower frequencies.
Parameters
----------
events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
dat : ndarray (dtype='float')
vector with the original data
s_freq : float
sampling frequency
limits : tuple of float
high and low frequencies for spindle band
ratio_thresh : float
ratio between spindle vs non-spindle amplitude
Returns
-------
ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
Notes
-----
In the original matlab script, it uses amplitude, not power. | [
"Estimate",
"the",
"ratio",
"in",
"power",
"between",
"spindle",
"band",
"and",
"lower",
"frequencies",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1755-L1801 |
24,866 | wonambi-python/wonambi | wonambi/detect/spindle.py | peak_in_power | def peak_in_power(events, dat, s_freq, method, value=None):
"""Define peak in power of the signal.
Parameters
----------
events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
dat : ndarray (dtype='float')
vector with the original data
s_freq : float
sampling frequency
method : str or None
'peak' or 'interval'. If None, values will be all NaN
value : float
size of the window around peak, or nothing (for 'interval')
Returns
-------
ndarray (dtype='float')
vector with peak frequency
"""
dat = diff(dat) # remove 1/f
peak = empty(events.shape[0])
peak.fill(nan)
if method is not None:
for i, one_event in enumerate(events):
if method == 'peak':
x0 = one_event[1] - value / 2 * s_freq
x1 = one_event[1] + value / 2 * s_freq
elif method == 'interval':
x0 = one_event[0]
x1 = one_event[2]
if x0 < 0 or x1 >= len(dat):
peak[i] = nan
else:
f, Pxx = periodogram(dat[x0:x1], s_freq)
idx_peak = Pxx[f < MAX_FREQUENCY_OF_INTEREST].argmax()
peak[i] = f[idx_peak]
return peak | python | def peak_in_power(events, dat, s_freq, method, value=None):
dat = diff(dat) # remove 1/f
peak = empty(events.shape[0])
peak.fill(nan)
if method is not None:
for i, one_event in enumerate(events):
if method == 'peak':
x0 = one_event[1] - value / 2 * s_freq
x1 = one_event[1] + value / 2 * s_freq
elif method == 'interval':
x0 = one_event[0]
x1 = one_event[2]
if x0 < 0 or x1 >= len(dat):
peak[i] = nan
else:
f, Pxx = periodogram(dat[x0:x1], s_freq)
idx_peak = Pxx[f < MAX_FREQUENCY_OF_INTEREST].argmax()
peak[i] = f[idx_peak]
return peak | [
"def",
"peak_in_power",
"(",
"events",
",",
"dat",
",",
"s_freq",
",",
"method",
",",
"value",
"=",
"None",
")",
":",
"dat",
"=",
"diff",
"(",
"dat",
")",
"# remove 1/f",
"peak",
"=",
"empty",
"(",
"events",
".",
"shape",
"[",
"0",
"]",
")",
"peak"... | Define peak in power of the signal.
Parameters
----------
events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
dat : ndarray (dtype='float')
vector with the original data
s_freq : float
sampling frequency
method : str or None
'peak' or 'interval'. If None, values will be all NaN
value : float
size of the window around peak, or nothing (for 'interval')
Returns
-------
ndarray (dtype='float')
vector with peak frequency | [
"Define",
"peak",
"in",
"power",
"of",
"the",
"signal",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1804-L1849 |
24,867 | wonambi-python/wonambi | wonambi/detect/spindle.py | power_in_band | def power_in_band(events, dat, s_freq, frequency):
"""Define power of the signal within frequency band.
Parameters
----------
events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
dat : ndarray (dtype='float')
vector with the original data
s_freq : float
sampling frequency
frequency : tuple of float
low and high frequency of spindle band, for window
Returns
-------
ndarray (dtype='float')
vector with power
"""
dat = diff(dat) # remove 1/f
pw = empty(events.shape[0])
pw.fill(nan)
for i, one_event in enumerate(events):
x0 = one_event[0]
x1 = one_event[2]
if x0 < 0 or x1 >= len(dat):
pw[i] = nan
else:
sf, Pxx = periodogram(dat[x0:x1], s_freq)
# find nearest frequencies in sf
b0 = asarray([abs(x - frequency[0]) for x in sf]).argmin()
b1 = asarray([abs(x - frequency[1]) for x in sf]).argmin()
pw[i] = mean(Pxx[b0:b1])
return pw | python | def power_in_band(events, dat, s_freq, frequency):
dat = diff(dat) # remove 1/f
pw = empty(events.shape[0])
pw.fill(nan)
for i, one_event in enumerate(events):
x0 = one_event[0]
x1 = one_event[2]
if x0 < 0 or x1 >= len(dat):
pw[i] = nan
else:
sf, Pxx = periodogram(dat[x0:x1], s_freq)
# find nearest frequencies in sf
b0 = asarray([abs(x - frequency[0]) for x in sf]).argmin()
b1 = asarray([abs(x - frequency[1]) for x in sf]).argmin()
pw[i] = mean(Pxx[b0:b1])
return pw | [
"def",
"power_in_band",
"(",
"events",
",",
"dat",
",",
"s_freq",
",",
"frequency",
")",
":",
"dat",
"=",
"diff",
"(",
"dat",
")",
"# remove 1/f",
"pw",
"=",
"empty",
"(",
"events",
".",
"shape",
"[",
"0",
"]",
")",
"pw",
".",
"fill",
"(",
"nan",
... | Define power of the signal within frequency band.
Parameters
----------
events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
dat : ndarray (dtype='float')
vector with the original data
s_freq : float
sampling frequency
frequency : tuple of float
low and high frequency of spindle band, for window
Returns
-------
ndarray (dtype='float')
vector with power | [
"Define",
"power",
"of",
"the",
"signal",
"within",
"frequency",
"band",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1852-L1890 |
24,868 | wonambi-python/wonambi | wonambi/detect/spindle.py | make_spindles | def make_spindles(events, power_peaks, powers, dat_det, dat_orig, time,
s_freq):
"""Create dict for each spindle, based on events of time points.
Parameters
----------
events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples, and peak frequency
power_peaks : ndarray (dtype='float')
peak in power spectrum for each event
powers : ndarray (dtype='float')
average power in power spectrum for each event
dat_det : ndarray (dtype='float')
vector with the data after detection-transformation (to compute peak)
dat_orig : ndarray (dtype='float')
vector with the raw data on which detection was performed
time : ndarray (dtype='float')
vector with time points
s_freq : float
sampling frequency
Returns
-------
list of dict
list of all the spindles, with information about start_time, peak_time,
end_time (s), peak_val (signal units), area_under_curve
(signal units * s), peak_freq (Hz)
"""
i, events = _remove_duplicate(events, dat_det)
power_peaks = power_peaks[i]
spindles = []
for i, one_peak, one_pwr in zip(events, power_peaks, powers):
one_spindle = {'start': time[i[0]],
'end': time[i[2] - 1],
'peak_time': time[i[1]],
'peak_val_det': dat_det[i[1]],
'peak_val_orig': dat_orig[i[1]],
'dur': (i[2] - i[0]) / s_freq,
'auc_det': sum(dat_det[i[0]:i[2]]) / s_freq,
'auc_orig': sum(dat_orig[i[0]:i[2]]) / s_freq,
'rms_det': sqrt(mean(square(dat_det[i[0]:i[2]]))),
'rms_orig': sqrt(mean(square(dat_orig[i[0]:i[2]]))),
'power_orig': one_pwr,
'peak_freq': one_peak,
'ptp_det': ptp(dat_det[i[0]:i[2]]),
'ptp_orig': ptp(dat_orig[i[0]:i[2]])
}
spindles.append(one_spindle)
return spindles | python | def make_spindles(events, power_peaks, powers, dat_det, dat_orig, time,
s_freq):
i, events = _remove_duplicate(events, dat_det)
power_peaks = power_peaks[i]
spindles = []
for i, one_peak, one_pwr in zip(events, power_peaks, powers):
one_spindle = {'start': time[i[0]],
'end': time[i[2] - 1],
'peak_time': time[i[1]],
'peak_val_det': dat_det[i[1]],
'peak_val_orig': dat_orig[i[1]],
'dur': (i[2] - i[0]) / s_freq,
'auc_det': sum(dat_det[i[0]:i[2]]) / s_freq,
'auc_orig': sum(dat_orig[i[0]:i[2]]) / s_freq,
'rms_det': sqrt(mean(square(dat_det[i[0]:i[2]]))),
'rms_orig': sqrt(mean(square(dat_orig[i[0]:i[2]]))),
'power_orig': one_pwr,
'peak_freq': one_peak,
'ptp_det': ptp(dat_det[i[0]:i[2]]),
'ptp_orig': ptp(dat_orig[i[0]:i[2]])
}
spindles.append(one_spindle)
return spindles | [
"def",
"make_spindles",
"(",
"events",
",",
"power_peaks",
",",
"powers",
",",
"dat_det",
",",
"dat_orig",
",",
"time",
",",
"s_freq",
")",
":",
"i",
",",
"events",
"=",
"_remove_duplicate",
"(",
"events",
",",
"dat_det",
")",
"power_peaks",
"=",
"power_pe... | Create dict for each spindle, based on events of time points.
Parameters
----------
events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples, and peak frequency
power_peaks : ndarray (dtype='float')
peak in power spectrum for each event
powers : ndarray (dtype='float')
average power in power spectrum for each event
dat_det : ndarray (dtype='float')
vector with the data after detection-transformation (to compute peak)
dat_orig : ndarray (dtype='float')
vector with the raw data on which detection was performed
time : ndarray (dtype='float')
vector with time points
s_freq : float
sampling frequency
Returns
-------
list of dict
list of all the spindles, with information about start_time, peak_time,
end_time (s), peak_val (signal units), area_under_curve
(signal units * s), peak_freq (Hz) | [
"Create",
"dict",
"for",
"each",
"spindle",
"based",
"on",
"events",
"of",
"time",
"points",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1893-L1943 |
24,869 | wonambi-python/wonambi | wonambi/detect/spindle.py | _remove_duplicate | def _remove_duplicate(old_events, dat):
"""Remove duplicates from the events.
Parameters
----------
old_events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
dat : ndarray (dtype='float')
vector with the data after detection-transformation (to compute peak)
Returns
-------
ndarray (dtype='int')
vector of indices of the events to keep
ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
Notes
-----
old_events is assumed to be sorted. It only checks for the start time and
end time. When two (or more) events have the same start time and the same
end time, then it takes the largest peak.
There is no tolerance, indices need to be identical.
"""
diff_events = diff(old_events, axis=0)
dupl = where((diff_events[:, 0] == 0) & (diff_events[:, 2] == 0))[0]
dupl += 1 # more convenient, it copies old_event first and then compares
n_nondupl_events = old_events.shape[0] - len(dupl)
new_events = zeros((n_nondupl_events, old_events.shape[1]), dtype='int')
if len(dupl):
lg.debug('Removing ' + str(len(dupl)) + ' duplicate events')
i = 0
indices = []
for i_old, one_old_event in enumerate(old_events):
if i_old not in dupl:
new_events[i, :] = one_old_event
i += 1
indices.append(i_old)
else:
peak_0 = new_events[i - 1, 1]
peak_1 = one_old_event[1]
if dat[peak_0] >= dat[peak_1]:
new_events[i - 1, 1] = peak_0
else:
new_events[i - 1, 1] = peak_1
return indices, new_events | python | def _remove_duplicate(old_events, dat):
diff_events = diff(old_events, axis=0)
dupl = where((diff_events[:, 0] == 0) & (diff_events[:, 2] == 0))[0]
dupl += 1 # more convenient, it copies old_event first and then compares
n_nondupl_events = old_events.shape[0] - len(dupl)
new_events = zeros((n_nondupl_events, old_events.shape[1]), dtype='int')
if len(dupl):
lg.debug('Removing ' + str(len(dupl)) + ' duplicate events')
i = 0
indices = []
for i_old, one_old_event in enumerate(old_events):
if i_old not in dupl:
new_events[i, :] = one_old_event
i += 1
indices.append(i_old)
else:
peak_0 = new_events[i - 1, 1]
peak_1 = one_old_event[1]
if dat[peak_0] >= dat[peak_1]:
new_events[i - 1, 1] = peak_0
else:
new_events[i - 1, 1] = peak_1
return indices, new_events | [
"def",
"_remove_duplicate",
"(",
"old_events",
",",
"dat",
")",
":",
"diff_events",
"=",
"diff",
"(",
"old_events",
",",
"axis",
"=",
"0",
")",
"dupl",
"=",
"where",
"(",
"(",
"diff_events",
"[",
":",
",",
"0",
"]",
"==",
"0",
")",
"&",
"(",
"diff_... | Remove duplicates from the events.
Parameters
----------
old_events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
dat : ndarray (dtype='float')
vector with the data after detection-transformation (to compute peak)
Returns
-------
ndarray (dtype='int')
vector of indices of the events to keep
ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
Notes
-----
old_events is assumed to be sorted. It only checks for the start time and
end time. When two (or more) events have the same start time and the same
end time, then it takes the largest peak.
There is no tolerance, indices need to be identical. | [
"Remove",
"duplicates",
"from",
"the",
"events",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1946-L1995 |
24,870 | wonambi-python/wonambi | wonambi/detect/spindle.py | _detect_start_end | def _detect_start_end(true_values):
"""From ndarray of bool values, return intervals of True values.
Parameters
----------
true_values : ndarray (dtype='bool')
array with bool values
Returns
-------
ndarray (dtype='int')
N x 2 matrix with starting and ending times.
"""
neg = zeros((1), dtype='bool')
int_values = asarray(concatenate((neg, true_values[:-1], neg)),
dtype='int')
# must discard last value to avoid axis out of bounds
cross_threshold = diff(int_values)
event_starts = where(cross_threshold == 1)[0]
event_ends = where(cross_threshold == -1)[0]
if len(event_starts):
events = vstack((event_starts, event_ends)).T
else:
events = None
return events | python | def _detect_start_end(true_values):
neg = zeros((1), dtype='bool')
int_values = asarray(concatenate((neg, true_values[:-1], neg)),
dtype='int')
# must discard last value to avoid axis out of bounds
cross_threshold = diff(int_values)
event_starts = where(cross_threshold == 1)[0]
event_ends = where(cross_threshold == -1)[0]
if len(event_starts):
events = vstack((event_starts, event_ends)).T
else:
events = None
return events | [
"def",
"_detect_start_end",
"(",
"true_values",
")",
":",
"neg",
"=",
"zeros",
"(",
"(",
"1",
")",
",",
"dtype",
"=",
"'bool'",
")",
"int_values",
"=",
"asarray",
"(",
"concatenate",
"(",
"(",
"neg",
",",
"true_values",
"[",
":",
"-",
"1",
"]",
",",
... | From ndarray of bool values, return intervals of True values.
Parameters
----------
true_values : ndarray (dtype='bool')
array with bool values
Returns
-------
ndarray (dtype='int')
N x 2 matrix with starting and ending times. | [
"From",
"ndarray",
"of",
"bool",
"values",
"return",
"intervals",
"of",
"True",
"values",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1998-L2026 |
24,871 | wonambi-python/wonambi | wonambi/detect/spindle.py | _merge_close | def _merge_close(dat, events, time, min_interval):
"""Merge together events separated by less than a minimum interval.
Parameters
----------
dat : ndarray (dtype='float')
vector with the data after selection-transformation
events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
time : ndarray (dtype='float')
vector with time points
min_interval : float
minimum delay between consecutive events, in seconds
Returns
-------
ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
"""
if not events.any():
return events
no_merge = time[events[1:, 0] - 1] - time[events[:-1, 2]] >= min_interval
if no_merge.any():
begs = concatenate([[events[0, 0]], events[1:, 0][no_merge]])
ends = concatenate([events[:-1, 2][no_merge], [events[-1, 2]]])
new_events = vstack((begs, ends)).T
else:
new_events = asarray([[events[0, 0], events[-1, 2]]])
# add the location of the peak in the middle
new_events = insert(new_events, 1, 0, axis=1)
for i in new_events:
if i[2] - i[0] >= 1:
i[1] = i[0] + argmax(dat[i[0]:i[2]])
return new_events | python | def _merge_close(dat, events, time, min_interval):
if not events.any():
return events
no_merge = time[events[1:, 0] - 1] - time[events[:-1, 2]] >= min_interval
if no_merge.any():
begs = concatenate([[events[0, 0]], events[1:, 0][no_merge]])
ends = concatenate([events[:-1, 2][no_merge], [events[-1, 2]]])
new_events = vstack((begs, ends)).T
else:
new_events = asarray([[events[0, 0], events[-1, 2]]])
# add the location of the peak in the middle
new_events = insert(new_events, 1, 0, axis=1)
for i in new_events:
if i[2] - i[0] >= 1:
i[1] = i[0] + argmax(dat[i[0]:i[2]])
return new_events | [
"def",
"_merge_close",
"(",
"dat",
",",
"events",
",",
"time",
",",
"min_interval",
")",
":",
"if",
"not",
"events",
".",
"any",
"(",
")",
":",
"return",
"events",
"no_merge",
"=",
"time",
"[",
"events",
"[",
"1",
":",
",",
"0",
"]",
"-",
"1",
"]... | Merge together events separated by less than a minimum interval.
Parameters
----------
dat : ndarray (dtype='float')
vector with the data after selection-transformation
events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
time : ndarray (dtype='float')
vector with time points
min_interval : float
minimum delay between consecutive events, in seconds
Returns
-------
ndarray (dtype='int')
N x 3 matrix with start, peak, end samples | [
"Merge",
"together",
"events",
"separated",
"by",
"less",
"than",
"a",
"minimum",
"interval",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L2068-L2106 |
24,872 | wonambi-python/wonambi | wonambi/detect/spindle.py | _wmorlet | def _wmorlet(f0, sd, sampling_rate, ns=5):
"""
adapted from nitime
returns a complex morlet wavelet in the time domain
Parameters
----------
f0 : center frequency
sd : standard deviation of frequency
sampling_rate : samplingrate
ns : window length in number of standard deviations
"""
st = 1. / (2. * pi * sd)
w_sz = float(int(ns * st * sampling_rate)) # half time window size
t = arange(-w_sz, w_sz + 1, dtype=float) / sampling_rate
w = (exp(-t ** 2 / (2. * st ** 2)) * exp(2j * pi * f0 * t) /
sqrt(sqrt(pi) * st * sampling_rate))
return w | python | def _wmorlet(f0, sd, sampling_rate, ns=5):
st = 1. / (2. * pi * sd)
w_sz = float(int(ns * st * sampling_rate)) # half time window size
t = arange(-w_sz, w_sz + 1, dtype=float) / sampling_rate
w = (exp(-t ** 2 / (2. * st ** 2)) * exp(2j * pi * f0 * t) /
sqrt(sqrt(pi) * st * sampling_rate))
return w | [
"def",
"_wmorlet",
"(",
"f0",
",",
"sd",
",",
"sampling_rate",
",",
"ns",
"=",
"5",
")",
":",
"st",
"=",
"1.",
"/",
"(",
"2.",
"*",
"pi",
"*",
"sd",
")",
"w_sz",
"=",
"float",
"(",
"int",
"(",
"ns",
"*",
"st",
"*",
"sampling_rate",
")",
")",
... | adapted from nitime
returns a complex morlet wavelet in the time domain
Parameters
----------
f0 : center frequency
sd : standard deviation of frequency
sampling_rate : samplingrate
ns : window length in number of standard deviations | [
"adapted",
"from",
"nitime"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L2109-L2127 |
24,873 | wonambi-python/wonambi | wonambi/detect/spindle.py | _realwavelets | def _realwavelets(s_freq, freqs, dur, width):
"""Create real wavelets, for UCSD.
Parameters
----------
s_freq : int
sampling frequency
freqs : ndarray
vector with frequencies of interest
dur : float
duration of the wavelets in s
width : float
parameter controlling gaussian shape
Returns
-------
ndarray
wavelets
"""
x = arange(-dur / 2, dur / 2, 1 / s_freq)
wavelets = empty((len(freqs), len(x)))
g = exp(-(pi * x ** 2) / width ** 2)
for i, one_freq in enumerate(freqs):
y = cos(2 * pi * x * one_freq)
wavelets[i, :] = y * g
return wavelets | python | def _realwavelets(s_freq, freqs, dur, width):
x = arange(-dur / 2, dur / 2, 1 / s_freq)
wavelets = empty((len(freqs), len(x)))
g = exp(-(pi * x ** 2) / width ** 2)
for i, one_freq in enumerate(freqs):
y = cos(2 * pi * x * one_freq)
wavelets[i, :] = y * g
return wavelets | [
"def",
"_realwavelets",
"(",
"s_freq",
",",
"freqs",
",",
"dur",
",",
"width",
")",
":",
"x",
"=",
"arange",
"(",
"-",
"dur",
"/",
"2",
",",
"dur",
"/",
"2",
",",
"1",
"/",
"s_freq",
")",
"wavelets",
"=",
"empty",
"(",
"(",
"len",
"(",
"freqs",... | Create real wavelets, for UCSD.
Parameters
----------
s_freq : int
sampling frequency
freqs : ndarray
vector with frequencies of interest
dur : float
duration of the wavelets in s
width : float
parameter controlling gaussian shape
Returns
-------
ndarray
wavelets | [
"Create",
"real",
"wavelets",
"for",
"UCSD",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L2130-L2158 |
24,874 | wonambi-python/wonambi | wonambi/widgets/detect_dialogs.py | SpindleDialog.count_channels | def count_channels(self):
"""If more than one channel selected, activate merge checkbox."""
merge = self.index['merge']
if len(self.idx_chan.selectedItems()) > 1:
if merge.isEnabled():
return
else:
merge.setEnabled(True)
else:
self.index['merge'].setCheckState(Qt.Unchecked)
self.index['merge'].setEnabled(False) | python | def count_channels(self):
merge = self.index['merge']
if len(self.idx_chan.selectedItems()) > 1:
if merge.isEnabled():
return
else:
merge.setEnabled(True)
else:
self.index['merge'].setCheckState(Qt.Unchecked)
self.index['merge'].setEnabled(False) | [
"def",
"count_channels",
"(",
"self",
")",
":",
"merge",
"=",
"self",
".",
"index",
"[",
"'merge'",
"]",
"if",
"len",
"(",
"self",
".",
"idx_chan",
".",
"selectedItems",
"(",
")",
")",
">",
"1",
":",
"if",
"merge",
".",
"isEnabled",
"(",
")",
":",
... | If more than one channel selected, activate merge checkbox. | [
"If",
"more",
"than",
"one",
"channel",
"selected",
"activate",
"merge",
"checkbox",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/detect_dialogs.py#L465-L476 |
24,875 | wonambi-python/wonambi | wonambi/trans/math.py | math | def math(data, operator=None, operator_name=None, axis=None):
"""Apply mathematical operation to each trial and channel individually.
Parameters
----------
data : instance of DataTime, DataFreq, or DataTimeFreq
operator : function or tuple of functions, optional
function(s) to run on the data.
operator_name : str or tuple of str, optional
name of the function(s) to run on the data.
axis : str, optional
for functions that accept it, which axis you should run it on.
Returns
-------
instance of Data
data where the trials underwent operator.
Raises
------
TypeError
If you pass both operator and operator_name.
ValueError
When you try to operate on an axis that has already been removed.
Notes
-----
operator and operator_name are mutually exclusive. operator_name is given
as shortcut for most common operations.
If a function accepts an 'axis' argument, you need to pass 'axis' to the
constructor. In this way, it'll apply the function to the correct
dimension.
The possible point-wise operator_name are:
'absolute', 'angle', 'dB' (=10 * log10), 'exp', 'log', 'sqrt', 'square',
'unwrap'
The operator_name's that need an axis, but do not remove it:
'hilbert', 'diff', 'detrend'
The operator_name's that need an axis and remove it:
'mean', 'median', 'mode', 'std'
Examples
--------
You can pass a single value or a tuple. The order starts from left to
right, so abs of the hilbert transform, should be:
>>> rms = math(data, operator_name=('hilbert', 'abs'), axis='time')
If you want to pass the power of three, use lambda (or partial):
>>> p3 = lambda x: power(x, 3)
>>> data_p3 = math(data, operator=p3)
Note that lambdas are fine with point-wise operation, but if you want them
to operate on axis, you need to pass ''axis'' as well, so that:
>>> std_ddof = lambda x, axis: std(x, axis, ddof=1)
>>> data_std = math(data, operator=std_ddof)
If you don't pass 'axis' in lambda, it'll never know on which axis the
function should be applied and you'll get unpredictable results.
If you want to pass a function that operates on an axis and removes it (for
example, if you want the max value over time), you need to add an argument
in your function called ''keepdims'' (the values won't be used):
>>> def func(x, axis, keepdims=None):
>>> return nanmax(x, axis=axis)
"""
if operator is not None and operator_name is not None:
raise TypeError('Parameters "operator" and "operator_name" are '
'mutually exclusive')
# turn input into a tuple of functions in operators
if operator_name is not None:
if isinstance(operator_name, str):
operator_name = (operator_name, )
operators = []
for one_operator_name in operator_name:
operators.append(eval(one_operator_name))
operator = tuple(operators)
# make it an iterable
if callable(operator):
operator = (operator, )
operations = []
for one_operator in operator:
on_axis = False
keepdims = True
try:
args = getfullargspec(one_operator).args
except TypeError:
lg.debug('func ' + str(one_operator) + ' is not a Python '
'function')
else:
if 'axis' in args:
on_axis = True
if axis is None:
raise TypeError('You need to specify an axis if you '
'use ' + one_operator.__name__ +
' (which applies to an axis)')
if 'keepdims' in args or one_operator in NOKEEPDIM:
keepdims = False
operations.append({'name': one_operator.__name__,
'func': one_operator,
'on_axis': on_axis,
'keepdims': keepdims,
})
output = data._copy()
if axis is not None:
idx_axis = data.index_of(axis)
first_op = True
for op in operations:
#lg.info('running operator: ' + op['name'])
func = op['func']
if func == mode:
func = lambda x, axis: mode(x, axis=axis)[0]
for i in range(output.number_of('trial')):
# don't copy original data, but use data if it's the first operation
if first_op:
x = data(trial=i)
else:
x = output(trial=i)
if op['on_axis']:
lg.debug('running ' + op['name'] + ' on ' + str(idx_axis))
try:
if func == diff:
lg.debug('Diff has one-point of zero padding')
x = _pad_one_axis_one_value(x, idx_axis)
output.data[i] = func(x, axis=idx_axis)
except IndexError:
raise ValueError('The axis ' + axis + ' does not '
'exist in [' +
', '.join(list(data.axis.keys())) + ']')
else:
lg.debug('running ' + op['name'] + ' on each datapoint')
output.data[i] = func(x)
first_op = False
if op['on_axis'] and not op['keepdims']:
del output.axis[axis]
return output | python | def math(data, operator=None, operator_name=None, axis=None):
if operator is not None and operator_name is not None:
raise TypeError('Parameters "operator" and "operator_name" are '
'mutually exclusive')
# turn input into a tuple of functions in operators
if operator_name is not None:
if isinstance(operator_name, str):
operator_name = (operator_name, )
operators = []
for one_operator_name in operator_name:
operators.append(eval(one_operator_name))
operator = tuple(operators)
# make it an iterable
if callable(operator):
operator = (operator, )
operations = []
for one_operator in operator:
on_axis = False
keepdims = True
try:
args = getfullargspec(one_operator).args
except TypeError:
lg.debug('func ' + str(one_operator) + ' is not a Python '
'function')
else:
if 'axis' in args:
on_axis = True
if axis is None:
raise TypeError('You need to specify an axis if you '
'use ' + one_operator.__name__ +
' (which applies to an axis)')
if 'keepdims' in args or one_operator in NOKEEPDIM:
keepdims = False
operations.append({'name': one_operator.__name__,
'func': one_operator,
'on_axis': on_axis,
'keepdims': keepdims,
})
output = data._copy()
if axis is not None:
idx_axis = data.index_of(axis)
first_op = True
for op in operations:
#lg.info('running operator: ' + op['name'])
func = op['func']
if func == mode:
func = lambda x, axis: mode(x, axis=axis)[0]
for i in range(output.number_of('trial')):
# don't copy original data, but use data if it's the first operation
if first_op:
x = data(trial=i)
else:
x = output(trial=i)
if op['on_axis']:
lg.debug('running ' + op['name'] + ' on ' + str(idx_axis))
try:
if func == diff:
lg.debug('Diff has one-point of zero padding')
x = _pad_one_axis_one_value(x, idx_axis)
output.data[i] = func(x, axis=idx_axis)
except IndexError:
raise ValueError('The axis ' + axis + ' does not '
'exist in [' +
', '.join(list(data.axis.keys())) + ']')
else:
lg.debug('running ' + op['name'] + ' on each datapoint')
output.data[i] = func(x)
first_op = False
if op['on_axis'] and not op['keepdims']:
del output.axis[axis]
return output | [
"def",
"math",
"(",
"data",
",",
"operator",
"=",
"None",
",",
"operator_name",
"=",
"None",
",",
"axis",
"=",
"None",
")",
":",
"if",
"operator",
"is",
"not",
"None",
"and",
"operator_name",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"'Param... | Apply mathematical operation to each trial and channel individually.
Parameters
----------
data : instance of DataTime, DataFreq, or DataTimeFreq
operator : function or tuple of functions, optional
function(s) to run on the data.
operator_name : str or tuple of str, optional
name of the function(s) to run on the data.
axis : str, optional
for functions that accept it, which axis you should run it on.
Returns
-------
instance of Data
data where the trials underwent operator.
Raises
------
TypeError
If you pass both operator and operator_name.
ValueError
When you try to operate on an axis that has already been removed.
Notes
-----
operator and operator_name are mutually exclusive. operator_name is given
as shortcut for most common operations.
If a function accepts an 'axis' argument, you need to pass 'axis' to the
constructor. In this way, it'll apply the function to the correct
dimension.
The possible point-wise operator_name are:
'absolute', 'angle', 'dB' (=10 * log10), 'exp', 'log', 'sqrt', 'square',
'unwrap'
The operator_name's that need an axis, but do not remove it:
'hilbert', 'diff', 'detrend'
The operator_name's that need an axis and remove it:
'mean', 'median', 'mode', 'std'
Examples
--------
You can pass a single value or a tuple. The order starts from left to
right, so abs of the hilbert transform, should be:
>>> rms = math(data, operator_name=('hilbert', 'abs'), axis='time')
If you want to pass the power of three, use lambda (or partial):
>>> p3 = lambda x: power(x, 3)
>>> data_p3 = math(data, operator=p3)
Note that lambdas are fine with point-wise operation, but if you want them
to operate on axis, you need to pass ''axis'' as well, so that:
>>> std_ddof = lambda x, axis: std(x, axis, ddof=1)
>>> data_std = math(data, operator=std_ddof)
If you don't pass 'axis' in lambda, it'll never know on which axis the
function should be applied and you'll get unpredictable results.
If you want to pass a function that operates on an axis and removes it (for
example, if you want the max value over time), you need to add an argument
in your function called ''keepdims'' (the values won't be used):
>>> def func(x, axis, keepdims=None):
>>> return nanmax(x, axis=axis) | [
"Apply",
"mathematical",
"operation",
"to",
"each",
"trial",
"and",
"channel",
"individually",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/math.py#L46-L209 |
24,876 | wonambi-python/wonambi | wonambi/trans/math.py | get_descriptives | def get_descriptives(data):
"""Get mean, SD, and mean and SD of log values.
Parameters
----------
data : ndarray
Data with segment as first dimension
and all other dimensions raveled into second dimension.
Returns
-------
dict of ndarray
each entry is a 1-D vector of descriptives over segment dimension
"""
output = {}
dat_log = log(abs(data))
output['mean'] = nanmean(data, axis=0)
output['sd'] = nanstd(data, axis=0)
output['mean_log'] = nanmean(dat_log, axis=0)
output['sd_log'] = nanstd(dat_log, axis=0)
return output | python | def get_descriptives(data):
output = {}
dat_log = log(abs(data))
output['mean'] = nanmean(data, axis=0)
output['sd'] = nanstd(data, axis=0)
output['mean_log'] = nanmean(dat_log, axis=0)
output['sd_log'] = nanstd(dat_log, axis=0)
return output | [
"def",
"get_descriptives",
"(",
"data",
")",
":",
"output",
"=",
"{",
"}",
"dat_log",
"=",
"log",
"(",
"abs",
"(",
"data",
")",
")",
"output",
"[",
"'mean'",
"]",
"=",
"nanmean",
"(",
"data",
",",
"axis",
"=",
"0",
")",
"output",
"[",
"'sd'",
"]"... | Get mean, SD, and mean and SD of log values.
Parameters
----------
data : ndarray
Data with segment as first dimension
and all other dimensions raveled into second dimension.
Returns
-------
dict of ndarray
each entry is a 1-D vector of descriptives over segment dimension | [
"Get",
"mean",
"SD",
"and",
"mean",
"and",
"SD",
"of",
"log",
"values",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/math.py#L211-L232 |
24,877 | wonambi-python/wonambi | wonambi/ioeeg/abf.py | _read_info_as_dict | def _read_info_as_dict(fid, values):
"""Convenience function to read info in axon data to a nicely organized
dict.
"""
output = {}
for key, fmt in values:
val = unpack(fmt, fid.read(calcsize(fmt)))
if len(val) == 1:
output[key] = val[0]
else:
output[key] = val
return output | python | def _read_info_as_dict(fid, values):
output = {}
for key, fmt in values:
val = unpack(fmt, fid.read(calcsize(fmt)))
if len(val) == 1:
output[key] = val[0]
else:
output[key] = val
return output | [
"def",
"_read_info_as_dict",
"(",
"fid",
",",
"values",
")",
":",
"output",
"=",
"{",
"}",
"for",
"key",
",",
"fmt",
"in",
"values",
":",
"val",
"=",
"unpack",
"(",
"fmt",
",",
"fid",
".",
"read",
"(",
"calcsize",
"(",
"fmt",
")",
")",
")",
"if",... | Convenience function to read info in axon data to a nicely organized
dict. | [
"Convenience",
"function",
"to",
"read",
"info",
"in",
"axon",
"data",
"to",
"a",
"nicely",
"organized",
"dict",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/abf.py#L251-L262 |
24,878 | wonambi-python/wonambi | wonambi/widgets/settings.py | read_settings | def read_settings(widget, value_name):
"""Read Settings information, either from INI or from default values.
Parameters
----------
widget : str
name of the widget
value_name : str
name of the value of interest.
Returns
-------
multiple types
type depends on the type in the default values.
"""
setting_name = widget + '/' + value_name
default_value = DEFAULTS[widget][value_name]
default_type = type(default_value)
if default_type is list:
default_type = type(default_value[0])
val = settings.value(setting_name, default_value, type=default_type)
return val | python | def read_settings(widget, value_name):
setting_name = widget + '/' + value_name
default_value = DEFAULTS[widget][value_name]
default_type = type(default_value)
if default_type is list:
default_type = type(default_value[0])
val = settings.value(setting_name, default_value, type=default_type)
return val | [
"def",
"read_settings",
"(",
"widget",
",",
"value_name",
")",
":",
"setting_name",
"=",
"widget",
"+",
"'/'",
"+",
"value_name",
"default_value",
"=",
"DEFAULTS",
"[",
"widget",
"]",
"[",
"value_name",
"]",
"default_type",
"=",
"type",
"(",
"default_value",
... | Read Settings information, either from INI or from default values.
Parameters
----------
widget : str
name of the widget
value_name : str
name of the value of interest.
Returns
-------
multiple types
type depends on the type in the default values. | [
"Read",
"Settings",
"information",
"either",
"from",
"INI",
"or",
"from",
"default",
"values",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/settings.py#L314-L338 |
24,879 | wonambi-python/wonambi | wonambi/widgets/settings.py | Settings.create_settings | def create_settings(self):
"""Create the widget, organized in two parts.
Notes
-----
When you add widgets in config, remember to update show_settings too
"""
bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Apply |
QDialogButtonBox.Cancel)
self.idx_ok = bbox.button(QDialogButtonBox.Ok)
self.idx_apply = bbox.button(QDialogButtonBox.Apply)
self.idx_cancel = bbox.button(QDialogButtonBox.Cancel)
bbox.clicked.connect(self.button_clicked)
page_list = QListWidget()
page_list.setSpacing(1)
page_list.currentRowChanged.connect(self.change_widget)
pages = ['General', 'Overview', 'Signals', 'Channels', 'Spectrum',
'Notes', 'Video']
for one_page in pages:
page_list.addItem(one_page)
self.stacked = QStackedWidget()
self.stacked.addWidget(self.config)
self.stacked.addWidget(self.parent.overview.config)
self.stacked.addWidget(self.parent.traces.config)
self.stacked.addWidget(self.parent.channels.config)
self.stacked.addWidget(self.parent.spectrum.config)
self.stacked.addWidget(self.parent.notes.config)
self.stacked.addWidget(self.parent.video.config)
hsplitter = QSplitter()
hsplitter.addWidget(page_list)
hsplitter.addWidget(self.stacked)
btnlayout = QHBoxLayout()
btnlayout.addStretch(1)
btnlayout.addWidget(bbox)
vlayout = QVBoxLayout()
vlayout.addWidget(hsplitter)
vlayout.addLayout(btnlayout)
self.setLayout(vlayout) | python | def create_settings(self):
bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Apply |
QDialogButtonBox.Cancel)
self.idx_ok = bbox.button(QDialogButtonBox.Ok)
self.idx_apply = bbox.button(QDialogButtonBox.Apply)
self.idx_cancel = bbox.button(QDialogButtonBox.Cancel)
bbox.clicked.connect(self.button_clicked)
page_list = QListWidget()
page_list.setSpacing(1)
page_list.currentRowChanged.connect(self.change_widget)
pages = ['General', 'Overview', 'Signals', 'Channels', 'Spectrum',
'Notes', 'Video']
for one_page in pages:
page_list.addItem(one_page)
self.stacked = QStackedWidget()
self.stacked.addWidget(self.config)
self.stacked.addWidget(self.parent.overview.config)
self.stacked.addWidget(self.parent.traces.config)
self.stacked.addWidget(self.parent.channels.config)
self.stacked.addWidget(self.parent.spectrum.config)
self.stacked.addWidget(self.parent.notes.config)
self.stacked.addWidget(self.parent.video.config)
hsplitter = QSplitter()
hsplitter.addWidget(page_list)
hsplitter.addWidget(self.stacked)
btnlayout = QHBoxLayout()
btnlayout.addStretch(1)
btnlayout.addWidget(bbox)
vlayout = QVBoxLayout()
vlayout.addWidget(hsplitter)
vlayout.addLayout(btnlayout)
self.setLayout(vlayout) | [
"def",
"create_settings",
"(",
"self",
")",
":",
"bbox",
"=",
"QDialogButtonBox",
"(",
"QDialogButtonBox",
".",
"Ok",
"|",
"QDialogButtonBox",
".",
"Apply",
"|",
"QDialogButtonBox",
".",
"Cancel",
")",
"self",
".",
"idx_ok",
"=",
"bbox",
".",
"button",
"(",
... | Create the widget, organized in two parts.
Notes
-----
When you add widgets in config, remember to update show_settings too | [
"Create",
"the",
"widget",
"organized",
"in",
"two",
"parts",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/settings.py#L90-L134 |
24,880 | wonambi-python/wonambi | wonambi/widgets/settings.py | Config.create_values | def create_values(self, value_names):
"""Read original values from the settings or the defaults.
Parameters
----------
value_names : list of str
list of value names to read
Returns
-------
dict
dictionary with the value names as keys
"""
output = {}
for value_name in value_names:
output[value_name] = read_settings(self.widget, value_name)
return output | python | def create_values(self, value_names):
output = {}
for value_name in value_names:
output[value_name] = read_settings(self.widget, value_name)
return output | [
"def",
"create_values",
"(",
"self",
",",
"value_names",
")",
":",
"output",
"=",
"{",
"}",
"for",
"value_name",
"in",
"value_names",
":",
"output",
"[",
"value_name",
"]",
"=",
"read_settings",
"(",
"self",
".",
"widget",
",",
"value_name",
")",
"return",... | Read original values from the settings or the defaults.
Parameters
----------
value_names : list of str
list of value names to read
Returns
-------
dict
dictionary with the value names as keys | [
"Read",
"original",
"values",
"from",
"the",
"settings",
"or",
"the",
"defaults",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/settings.py#L213-L230 |
24,881 | wonambi-python/wonambi | wonambi/widgets/settings.py | Config.get_values | def get_values(self):
"""Get values from the GUI and save them in preference file."""
for value_name, widget in self.index.items():
self.value[value_name] = widget.get_value(self.value[value_name])
setting_name = self.widget + '/' + value_name
settings.setValue(setting_name, self.value[value_name]) | python | def get_values(self):
for value_name, widget in self.index.items():
self.value[value_name] = widget.get_value(self.value[value_name])
setting_name = self.widget + '/' + value_name
settings.setValue(setting_name, self.value[value_name]) | [
"def",
"get_values",
"(",
"self",
")",
":",
"for",
"value_name",
",",
"widget",
"in",
"self",
".",
"index",
".",
"items",
"(",
")",
":",
"self",
".",
"value",
"[",
"value_name",
"]",
"=",
"widget",
".",
"get_value",
"(",
"self",
".",
"value",
"[",
... | Get values from the GUI and save them in preference file. | [
"Get",
"values",
"from",
"the",
"GUI",
"and",
"save",
"them",
"in",
"preference",
"file",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/settings.py#L238-L244 |
24,882 | wonambi-python/wonambi | wonambi/widgets/settings.py | Config.put_values | def put_values(self):
"""Put values to the GUI.
Notes
-----
In addition, when one small widget has been changed, it calls
set_modified, so that we know that the preference widget was modified.
"""
for value_name, widget in self.index.items():
widget.set_value(self.value[value_name])
widget.connect(self.set_modified) | python | def put_values(self):
for value_name, widget in self.index.items():
widget.set_value(self.value[value_name])
widget.connect(self.set_modified) | [
"def",
"put_values",
"(",
"self",
")",
":",
"for",
"value_name",
",",
"widget",
"in",
"self",
".",
"index",
".",
"items",
"(",
")",
":",
"widget",
".",
"set_value",
"(",
"self",
".",
"value",
"[",
"value_name",
"]",
")",
"widget",
".",
"connect",
"("... | Put values to the GUI.
Notes
-----
In addition, when one small widget has been changed, it calls
set_modified, so that we know that the preference widget was modified. | [
"Put",
"values",
"to",
"the",
"GUI",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/settings.py#L246-L257 |
24,883 | wonambi-python/wonambi | wonambi/datatype.py | _get_indices | def _get_indices(values, selected, tolerance):
"""Get indices based on user-selected values.
Parameters
----------
values : ndarray (any dtype)
values present in the axis.
selected : ndarray (any dtype) or tuple or list
values selected by the user
tolerance : float
avoid rounding errors.
Returns
-------
idx_data : list of int
indices of row/column to select the data
idx_output : list of int
indices of row/column to copy into output
Notes
-----
This function is probably not very fast, but it's pretty robust. It keeps
the order, which is extremely important.
If you use values in the self.axis, you don't need to specify tolerance.
However, if you specify arbitrary points, floating point errors might
affect the actual values. Of course, using tolerance is much slower.
Maybe tolerance should be part of Select instead of here.
"""
idx_data = []
idx_output = []
for idx_of_selected, one_selected in enumerate(selected):
if tolerance is None or values.dtype.kind == 'U':
idx_of_data = where(values == one_selected)[0]
else:
idx_of_data = where(abs(values - one_selected) <= tolerance)[0] # actual use min
if len(idx_of_data) > 0:
idx_data.append(idx_of_data[0])
idx_output.append(idx_of_selected)
return idx_data, idx_output | python | def _get_indices(values, selected, tolerance):
idx_data = []
idx_output = []
for idx_of_selected, one_selected in enumerate(selected):
if tolerance is None or values.dtype.kind == 'U':
idx_of_data = where(values == one_selected)[0]
else:
idx_of_data = where(abs(values - one_selected) <= tolerance)[0] # actual use min
if len(idx_of_data) > 0:
idx_data.append(idx_of_data[0])
idx_output.append(idx_of_selected)
return idx_data, idx_output | [
"def",
"_get_indices",
"(",
"values",
",",
"selected",
",",
"tolerance",
")",
":",
"idx_data",
"=",
"[",
"]",
"idx_output",
"=",
"[",
"]",
"for",
"idx_of_selected",
",",
"one_selected",
"in",
"enumerate",
"(",
"selected",
")",
":",
"if",
"tolerance",
"is",... | Get indices based on user-selected values.
Parameters
----------
values : ndarray (any dtype)
values present in the axis.
selected : ndarray (any dtype) or tuple or list
values selected by the user
tolerance : float
avoid rounding errors.
Returns
-------
idx_data : list of int
indices of row/column to select the data
idx_output : list of int
indices of row/column to copy into output
Notes
-----
This function is probably not very fast, but it's pretty robust. It keeps
the order, which is extremely important.
If you use values in the self.axis, you don't need to specify tolerance.
However, if you specify arbitrary points, floating point errors might
affect the actual values. Of course, using tolerance is much slower.
Maybe tolerance should be part of Select instead of here. | [
"Get",
"indices",
"based",
"on",
"user",
"-",
"selected",
"values",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/datatype.py#L468-L512 |
24,884 | wonambi-python/wonambi | wonambi/datatype.py | Data.number_of | def number_of(self, axis):
"""Return the number of in one axis, as generally as possible.
Parameters
----------
axis : str
Name of the axis (such as 'trial', 'time', etc)
Returns
-------
int or ndarray (dtype='int')
number of trial (as int) or number of element in the selected
axis (if any of the other axiss) as 1d array.
Raises
------
KeyError
If the requested axis is not in the data.
Notes
-----
or is it better to catch the exception?
"""
if axis == 'trial':
return len(self.data)
else:
n_trial = self.number_of('trial')
output = empty(n_trial, dtype='int')
for i in range(n_trial):
output[i] = len(self.axis[axis][i])
return output | python | def number_of(self, axis):
if axis == 'trial':
return len(self.data)
else:
n_trial = self.number_of('trial')
output = empty(n_trial, dtype='int')
for i in range(n_trial):
output[i] = len(self.axis[axis][i])
return output | [
"def",
"number_of",
"(",
"self",
",",
"axis",
")",
":",
"if",
"axis",
"==",
"'trial'",
":",
"return",
"len",
"(",
"self",
".",
"data",
")",
"else",
":",
"n_trial",
"=",
"self",
".",
"number_of",
"(",
"'trial'",
")",
"output",
"=",
"empty",
"(",
"n_... | Return the number of in one axis, as generally as possible.
Parameters
----------
axis : str
Name of the axis (such as 'trial', 'time', etc)
Returns
-------
int or ndarray (dtype='int')
number of trial (as int) or number of element in the selected
axis (if any of the other axiss) as 1d array.
Raises
------
KeyError
If the requested axis is not in the data.
Notes
-----
or is it better to catch the exception? | [
"Return",
"the",
"number",
"of",
"in",
"one",
"axis",
"as",
"generally",
"as",
"possible",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/datatype.py#L216-L248 |
24,885 | wonambi-python/wonambi | wonambi/datatype.py | Data._copy | def _copy(self, axis=True, attr=True, data=False):
"""Create a new instance of Data, but does not copy the data
necessarily.
Parameters
----------
axis : bool, optional
deep copy the axes (default: True)
attr : bool, optional
deep copy the attributes (default: True)
data : bool, optional
deep copy the data (default: False)
Returns
-------
instance of Data (or ChanTime, ChanFreq, ChanTimeFreq)
copy of the data, but without the actual data
Notes
-----
It's important that we copy all the relevant information here. If you
add new attributes, you should add them here.
Remember that it deep-copies all the information, so if you copy data
the size might become really large.
"""
cdata = type(self)() # create instance of the same class
cdata.s_freq = self.s_freq
cdata.start_time = self.start_time
if axis:
cdata.axis = deepcopy(self.axis)
else:
cdata_axis = OrderedDict()
for axis_name in self.axis:
cdata_axis[axis_name] = array([], dtype='O')
cdata.axis = cdata_axis
if attr:
cdata.attr = deepcopy(self.attr)
if data:
cdata.data = deepcopy(self.data)
else:
# empty data with the correct number of trials
cdata.data = empty(self.number_of('trial'), dtype='O')
return cdata | python | def _copy(self, axis=True, attr=True, data=False):
cdata = type(self)() # create instance of the same class
cdata.s_freq = self.s_freq
cdata.start_time = self.start_time
if axis:
cdata.axis = deepcopy(self.axis)
else:
cdata_axis = OrderedDict()
for axis_name in self.axis:
cdata_axis[axis_name] = array([], dtype='O')
cdata.axis = cdata_axis
if attr:
cdata.attr = deepcopy(self.attr)
if data:
cdata.data = deepcopy(self.data)
else:
# empty data with the correct number of trials
cdata.data = empty(self.number_of('trial'), dtype='O')
return cdata | [
"def",
"_copy",
"(",
"self",
",",
"axis",
"=",
"True",
",",
"attr",
"=",
"True",
",",
"data",
"=",
"False",
")",
":",
"cdata",
"=",
"type",
"(",
"self",
")",
"(",
")",
"# create instance of the same class",
"cdata",
".",
"s_freq",
"=",
"self",
".",
"... | Create a new instance of Data, but does not copy the data
necessarily.
Parameters
----------
axis : bool, optional
deep copy the axes (default: True)
attr : bool, optional
deep copy the attributes (default: True)
data : bool, optional
deep copy the data (default: False)
Returns
-------
instance of Data (or ChanTime, ChanFreq, ChanTimeFreq)
copy of the data, but without the actual data
Notes
-----
It's important that we copy all the relevant information here. If you
add new attributes, you should add them here.
Remember that it deep-copies all the information, so if you copy data
the size might become really large. | [
"Create",
"a",
"new",
"instance",
"of",
"Data",
"but",
"does",
"not",
"copy",
"the",
"data",
"necessarily",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/datatype.py#L302-L351 |
24,886 | wonambi-python/wonambi | wonambi/datatype.py | Data.export | def export(self, filename, export_format='FieldTrip', **options):
"""Export data in other formats.
Parameters
----------
filename : path to file
file to write
export_format : str, optional
supported export format is currently FieldTrip, EDF, FIFF, Wonambi,
BrainVision
Notes
-----
'edf' takes an optional argument "physical_max", see write_edf.
'wonambi' takes an optional argument "subj_id", see write_wonambi.
wonambi format creates two files, one .won with the dataset info as json
file and one .dat with the memmap recordings.
'brainvision' takes an additional argument ("markers") which is a list
of dictionaries with fields:
"name" : str (name of the marker),
"start" : float (start time in seconds)
"end" : float (end time in seconds)
'bids' has an optional argument "markers", like in 'brainvision'
"""
filename = Path(filename)
filename.parent.mkdir(parents=True, exist_ok=True)
export_format = export_format.lower()
if export_format == 'edf':
from .ioeeg import write_edf # avoid circular import
write_edf(self, filename, **options)
elif export_format == 'fieldtrip':
from .ioeeg import write_fieldtrip # avoid circular import
write_fieldtrip(self, filename)
elif export_format == 'mnefiff':
from .ioeeg import write_mnefiff
write_mnefiff(self, filename)
elif export_format == 'wonambi':
from .ioeeg import write_wonambi
write_wonambi(self, filename, **options)
elif export_format == 'brainvision':
from .ioeeg import write_brainvision
write_brainvision(self, filename, **options)
elif export_format == 'bids':
from .ioeeg import write_bids
write_bids(self, filename, **options)
else:
raise ValueError('Cannot export to ' + export_format) | python | def export(self, filename, export_format='FieldTrip', **options):
filename = Path(filename)
filename.parent.mkdir(parents=True, exist_ok=True)
export_format = export_format.lower()
if export_format == 'edf':
from .ioeeg import write_edf # avoid circular import
write_edf(self, filename, **options)
elif export_format == 'fieldtrip':
from .ioeeg import write_fieldtrip # avoid circular import
write_fieldtrip(self, filename)
elif export_format == 'mnefiff':
from .ioeeg import write_mnefiff
write_mnefiff(self, filename)
elif export_format == 'wonambi':
from .ioeeg import write_wonambi
write_wonambi(self, filename, **options)
elif export_format == 'brainvision':
from .ioeeg import write_brainvision
write_brainvision(self, filename, **options)
elif export_format == 'bids':
from .ioeeg import write_bids
write_bids(self, filename, **options)
else:
raise ValueError('Cannot export to ' + export_format) | [
"def",
"export",
"(",
"self",
",",
"filename",
",",
"export_format",
"=",
"'FieldTrip'",
",",
"*",
"*",
"options",
")",
":",
"filename",
"=",
"Path",
"(",
"filename",
")",
"filename",
".",
"parent",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exis... | Export data in other formats.
Parameters
----------
filename : path to file
file to write
export_format : str, optional
supported export format is currently FieldTrip, EDF, FIFF, Wonambi,
BrainVision
Notes
-----
'edf' takes an optional argument "physical_max", see write_edf.
'wonambi' takes an optional argument "subj_id", see write_wonambi.
wonambi format creates two files, one .won with the dataset info as json
file and one .dat with the memmap recordings.
'brainvision' takes an additional argument ("markers") which is a list
of dictionaries with fields:
"name" : str (name of the marker),
"start" : float (start time in seconds)
"end" : float (end time in seconds)
'bids' has an optional argument "markers", like in 'brainvision' | [
"Export",
"data",
"in",
"other",
"formats",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/datatype.py#L353-L410 |
24,887 | wonambi-python/wonambi | wonambi/widgets/channels.py | ChannelsGroup.highlight_channels | def highlight_channels(self, l, selected_chan):
"""Highlight channels in the list of channels.
Parameters
----------
selected_chan : list of str
channels to indicate as selected.
"""
for row in range(l.count()):
item = l.item(row)
if item.text() in selected_chan:
item.setSelected(True)
else:
item.setSelected(False) | python | def highlight_channels(self, l, selected_chan):
for row in range(l.count()):
item = l.item(row)
if item.text() in selected_chan:
item.setSelected(True)
else:
item.setSelected(False) | [
"def",
"highlight_channels",
"(",
"self",
",",
"l",
",",
"selected_chan",
")",
":",
"for",
"row",
"in",
"range",
"(",
"l",
".",
"count",
"(",
")",
")",
":",
"item",
"=",
"l",
".",
"item",
"(",
"row",
")",
"if",
"item",
".",
"text",
"(",
")",
"i... | Highlight channels in the list of channels.
Parameters
----------
selected_chan : list of str
channels to indicate as selected. | [
"Highlight",
"channels",
"in",
"the",
"list",
"of",
"channels",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L196-L209 |
24,888 | wonambi-python/wonambi | wonambi/widgets/channels.py | ChannelsGroup.rereference | def rereference(self):
"""Automatically highlight channels to use as reference, based on
selected channels."""
selectedItems = self.idx_l0.selectedItems()
chan_to_plot = []
for selected in selectedItems:
chan_to_plot.append(selected.text())
self.highlight_channels(self.idx_l1, chan_to_plot) | python | def rereference(self):
selectedItems = self.idx_l0.selectedItems()
chan_to_plot = []
for selected in selectedItems:
chan_to_plot.append(selected.text())
self.highlight_channels(self.idx_l1, chan_to_plot) | [
"def",
"rereference",
"(",
"self",
")",
":",
"selectedItems",
"=",
"self",
".",
"idx_l0",
".",
"selectedItems",
"(",
")",
"chan_to_plot",
"=",
"[",
"]",
"for",
"selected",
"in",
"selectedItems",
":",
"chan_to_plot",
".",
"append",
"(",
"selected",
".",
"te... | Automatically highlight channels to use as reference, based on
selected channels. | [
"Automatically",
"highlight",
"channels",
"to",
"use",
"as",
"reference",
"based",
"on",
"selected",
"channels",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L211-L219 |
24,889 | wonambi-python/wonambi | wonambi/widgets/channels.py | ChannelsGroup.get_info | def get_info(self):
"""Get the information about the channel groups.
Returns
-------
dict
information about this channel group
Notes
-----
The items in selectedItems() are ordered based on the user's selection
(which appears pretty random). It's more consistent to use the same
order of the main channel list. That's why the additional for-loop
is necessary. We don't care about the order of the reference channels.
"""
selectedItems = self.idx_l0.selectedItems()
selected_chan = [x.text() for x in selectedItems]
chan_to_plot = []
for chan in self.chan_name + ['_REF']:
if chan in selected_chan:
chan_to_plot.append(chan)
selectedItems = self.idx_l1.selectedItems()
ref_chan = []
for selected in selectedItems:
ref_chan.append(selected.text())
hp = self.idx_hp.value()
if hp == 0:
low_cut = None
else:
low_cut = hp
lp = self.idx_lp.value()
if lp == 0:
high_cut = None
else:
high_cut = lp
scale = self.idx_scale.value()
group_info = {'name': self.group_name,
'chan_to_plot': chan_to_plot,
'ref_chan': ref_chan,
'hp': low_cut,
'lp': high_cut,
'scale': float(scale),
'color': self.idx_color
}
return group_info | python | def get_info(self):
selectedItems = self.idx_l0.selectedItems()
selected_chan = [x.text() for x in selectedItems]
chan_to_plot = []
for chan in self.chan_name + ['_REF']:
if chan in selected_chan:
chan_to_plot.append(chan)
selectedItems = self.idx_l1.selectedItems()
ref_chan = []
for selected in selectedItems:
ref_chan.append(selected.text())
hp = self.idx_hp.value()
if hp == 0:
low_cut = None
else:
low_cut = hp
lp = self.idx_lp.value()
if lp == 0:
high_cut = None
else:
high_cut = lp
scale = self.idx_scale.value()
group_info = {'name': self.group_name,
'chan_to_plot': chan_to_plot,
'ref_chan': ref_chan,
'hp': low_cut,
'lp': high_cut,
'scale': float(scale),
'color': self.idx_color
}
return group_info | [
"def",
"get_info",
"(",
"self",
")",
":",
"selectedItems",
"=",
"self",
".",
"idx_l0",
".",
"selectedItems",
"(",
")",
"selected_chan",
"=",
"[",
"x",
".",
"text",
"(",
")",
"for",
"x",
"in",
"selectedItems",
"]",
"chan_to_plot",
"=",
"[",
"]",
"for",
... | Get the information about the channel groups.
Returns
-------
dict
information about this channel group
Notes
-----
The items in selectedItems() are ordered based on the user's selection
(which appears pretty random). It's more consistent to use the same
order of the main channel list. That's why the additional for-loop
is necessary. We don't care about the order of the reference channels. | [
"Get",
"the",
"information",
"about",
"the",
"channel",
"groups",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L221-L271 |
24,890 | wonambi-python/wonambi | wonambi/widgets/channels.py | Channels.create | def create(self):
"""Create Channels Widget"""
add_button = QPushButton('New')
add_button.clicked.connect(self.new_group)
color_button = QPushButton('Color')
color_button.clicked.connect(self.color_group)
del_button = QPushButton('Delete')
del_button.clicked.connect(self.del_group)
apply_button = QPushButton('Apply')
apply_button.clicked.connect(self.apply)
self.button_add = add_button
self.button_color = color_button
self.button_del = del_button
self.button_apply = apply_button
buttons = QGridLayout()
buttons.addWidget(add_button, 0, 0)
buttons.addWidget(color_button, 1, 0)
buttons.addWidget(del_button, 0, 1)
buttons.addWidget(apply_button, 1, 1)
self.tabs = QTabWidget()
layout = QVBoxLayout()
layout.addLayout(buttons)
layout.addWidget(self.tabs)
self.setLayout(layout)
self.setEnabled(False)
self.button_color.setEnabled(False)
self.button_del.setEnabled(False)
self.button_apply.setEnabled(False) | python | def create(self):
add_button = QPushButton('New')
add_button.clicked.connect(self.new_group)
color_button = QPushButton('Color')
color_button.clicked.connect(self.color_group)
del_button = QPushButton('Delete')
del_button.clicked.connect(self.del_group)
apply_button = QPushButton('Apply')
apply_button.clicked.connect(self.apply)
self.button_add = add_button
self.button_color = color_button
self.button_del = del_button
self.button_apply = apply_button
buttons = QGridLayout()
buttons.addWidget(add_button, 0, 0)
buttons.addWidget(color_button, 1, 0)
buttons.addWidget(del_button, 0, 1)
buttons.addWidget(apply_button, 1, 1)
self.tabs = QTabWidget()
layout = QVBoxLayout()
layout.addLayout(buttons)
layout.addWidget(self.tabs)
self.setLayout(layout)
self.setEnabled(False)
self.button_color.setEnabled(False)
self.button_del.setEnabled(False)
self.button_apply.setEnabled(False) | [
"def",
"create",
"(",
"self",
")",
":",
"add_button",
"=",
"QPushButton",
"(",
"'New'",
")",
"add_button",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"new_group",
")",
"color_button",
"=",
"QPushButton",
"(",
"'Color'",
")",
"color_button",
".",
"cl... | Create Channels Widget | [
"Create",
"Channels",
"Widget"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L305-L338 |
24,891 | wonambi-python/wonambi | wonambi/widgets/channels.py | Channels.create_action | def create_action(self):
"""Create actions related to channel selection."""
actions = {}
act = QAction('Load Montage...', self)
act.triggered.connect(self.load_channels)
act.setEnabled(False)
actions['load_channels'] = act
act = QAction('Save Montage...', self)
act.triggered.connect(self.save_channels)
act.setEnabled(False)
actions['save_channels'] = act
self.action = actions | python | def create_action(self):
actions = {}
act = QAction('Load Montage...', self)
act.triggered.connect(self.load_channels)
act.setEnabled(False)
actions['load_channels'] = act
act = QAction('Save Montage...', self)
act.triggered.connect(self.save_channels)
act.setEnabled(False)
actions['save_channels'] = act
self.action = actions | [
"def",
"create_action",
"(",
"self",
")",
":",
"actions",
"=",
"{",
"}",
"act",
"=",
"QAction",
"(",
"'Load Montage...'",
",",
"self",
")",
"act",
".",
"triggered",
".",
"connect",
"(",
"self",
".",
"load_channels",
")",
"act",
".",
"setEnabled",
"(",
... | Create actions related to channel selection. | [
"Create",
"actions",
"related",
"to",
"channel",
"selection",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L340-L354 |
24,892 | wonambi-python/wonambi | wonambi/widgets/channels.py | Channels.new_group | def new_group(self, checked=False, test_name=None):
"""Create a new channel group.
Parameters
----------
checked : bool
comes from QAbstractButton.clicked
test_name : str
used for testing purposes to avoid modal window
Notes
-----
Don't call self.apply() just yet, only if the user wants it.
"""
chan_name = self.parent.labels.chan_name
if chan_name is None:
msg = 'No dataset loaded'
self.parent.statusBar().showMessage(msg)
lg.debug(msg)
else:
if test_name is None:
new_name = QInputDialog.getText(self, 'New Channel Group',
'Enter Name')
else:
new_name = [test_name, True] # like output of getText
if new_name[1]:
s_freq = self.parent.info.dataset.header['s_freq']
group = ChannelsGroup(chan_name, new_name[0],
self.config.value, s_freq)
self.tabs.addTab(group, new_name[0])
self.tabs.setCurrentIndex(self.tabs.currentIndex() + 1)
# activate buttons
self.button_color.setEnabled(True)
self.button_del.setEnabled(True)
self.button_apply.setEnabled(True) | python | def new_group(self, checked=False, test_name=None):
chan_name = self.parent.labels.chan_name
if chan_name is None:
msg = 'No dataset loaded'
self.parent.statusBar().showMessage(msg)
lg.debug(msg)
else:
if test_name is None:
new_name = QInputDialog.getText(self, 'New Channel Group',
'Enter Name')
else:
new_name = [test_name, True] # like output of getText
if new_name[1]:
s_freq = self.parent.info.dataset.header['s_freq']
group = ChannelsGroup(chan_name, new_name[0],
self.config.value, s_freq)
self.tabs.addTab(group, new_name[0])
self.tabs.setCurrentIndex(self.tabs.currentIndex() + 1)
# activate buttons
self.button_color.setEnabled(True)
self.button_del.setEnabled(True)
self.button_apply.setEnabled(True) | [
"def",
"new_group",
"(",
"self",
",",
"checked",
"=",
"False",
",",
"test_name",
"=",
"None",
")",
":",
"chan_name",
"=",
"self",
".",
"parent",
".",
"labels",
".",
"chan_name",
"if",
"chan_name",
"is",
"None",
":",
"msg",
"=",
"'No dataset loaded'",
"se... | Create a new channel group.
Parameters
----------
checked : bool
comes from QAbstractButton.clicked
test_name : str
used for testing purposes to avoid modal window
Notes
-----
Don't call self.apply() just yet, only if the user wants it. | [
"Create",
"a",
"new",
"channel",
"group",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L361-L398 |
24,893 | wonambi-python/wonambi | wonambi/widgets/channels.py | Channels.color_group | def color_group(self, checked=False, test_color=None):
"""Change the color of the group."""
group = self.tabs.currentWidget()
if test_color is None:
newcolor = QColorDialog.getColor(group.idx_color)
else:
newcolor = test_color
group.idx_color = newcolor
self.apply() | python | def color_group(self, checked=False, test_color=None):
group = self.tabs.currentWidget()
if test_color is None:
newcolor = QColorDialog.getColor(group.idx_color)
else:
newcolor = test_color
group.idx_color = newcolor
self.apply() | [
"def",
"color_group",
"(",
"self",
",",
"checked",
"=",
"False",
",",
"test_color",
"=",
"None",
")",
":",
"group",
"=",
"self",
".",
"tabs",
".",
"currentWidget",
"(",
")",
"if",
"test_color",
"is",
"None",
":",
"newcolor",
"=",
"QColorDialog",
".",
"... | Change the color of the group. | [
"Change",
"the",
"color",
"of",
"the",
"group",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L400-L409 |
24,894 | wonambi-python/wonambi | wonambi/widgets/channels.py | Channels.del_group | def del_group(self):
"""Delete current group."""
idx = self.tabs.currentIndex()
self.tabs.removeTab(idx)
self.apply() | python | def del_group(self):
idx = self.tabs.currentIndex()
self.tabs.removeTab(idx)
self.apply() | [
"def",
"del_group",
"(",
"self",
")",
":",
"idx",
"=",
"self",
".",
"tabs",
".",
"currentIndex",
"(",
")",
"self",
".",
"tabs",
".",
"removeTab",
"(",
"idx",
")",
"self",
".",
"apply",
"(",
")"
] | Delete current group. | [
"Delete",
"current",
"group",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L411-L416 |
24,895 | wonambi-python/wonambi | wonambi/widgets/channels.py | Channels.apply | def apply(self):
"""Apply changes to the plots."""
self.read_group_info()
if self.tabs.count() == 0:
# disactivate buttons
self.button_color.setEnabled(False)
self.button_del.setEnabled(False)
self.button_apply.setEnabled(False)
else:
# activate buttons
self.button_color.setEnabled(True)
self.button_del.setEnabled(True)
self.button_apply.setEnabled(True)
if self.groups:
self.parent.overview.update_position()
self.parent.spectrum.update()
self.parent.notes.enable_events()
else:
self.parent.traces.reset()
self.parent.spectrum.reset()
self.parent.notes.enable_events() | python | def apply(self):
self.read_group_info()
if self.tabs.count() == 0:
# disactivate buttons
self.button_color.setEnabled(False)
self.button_del.setEnabled(False)
self.button_apply.setEnabled(False)
else:
# activate buttons
self.button_color.setEnabled(True)
self.button_del.setEnabled(True)
self.button_apply.setEnabled(True)
if self.groups:
self.parent.overview.update_position()
self.parent.spectrum.update()
self.parent.notes.enable_events()
else:
self.parent.traces.reset()
self.parent.spectrum.reset()
self.parent.notes.enable_events() | [
"def",
"apply",
"(",
"self",
")",
":",
"self",
".",
"read_group_info",
"(",
")",
"if",
"self",
".",
"tabs",
".",
"count",
"(",
")",
"==",
"0",
":",
"# disactivate buttons",
"self",
".",
"button_color",
".",
"setEnabled",
"(",
"False",
")",
"self",
".",... | Apply changes to the plots. | [
"Apply",
"changes",
"to",
"the",
"plots",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L418-L440 |
24,896 | wonambi-python/wonambi | wonambi/widgets/channels.py | Channels.read_group_info | def read_group_info(self):
"""Get information about groups directly from the widget."""
self.groups = []
for i in range(self.tabs.count()):
one_group = self.tabs.widget(i).get_info()
# one_group['name'] = self.tabs.tabText(i)
self.groups.append(one_group) | python | def read_group_info(self):
self.groups = []
for i in range(self.tabs.count()):
one_group = self.tabs.widget(i).get_info()
# one_group['name'] = self.tabs.tabText(i)
self.groups.append(one_group) | [
"def",
"read_group_info",
"(",
"self",
")",
":",
"self",
".",
"groups",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"tabs",
".",
"count",
"(",
")",
")",
":",
"one_group",
"=",
"self",
".",
"tabs",
".",
"widget",
"(",
"i",
")",
"... | Get information about groups directly from the widget. | [
"Get",
"information",
"about",
"groups",
"directly",
"from",
"the",
"widget",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L442-L448 |
24,897 | wonambi-python/wonambi | wonambi/widgets/channels.py | Channels.load_channels | def load_channels(self, checked=False, test_name=None):
"""Load channel groups from file.
Parameters
----------
test_name : path to file
when debugging the function, you can open a channels file from the
command line
"""
chan_name = self.parent.labels.chan_name
if self.filename is not None:
filename = self.filename
elif self.parent.info.filename is not None:
filename = (splitext(self.parent.info.filename)[0] +
'_channels.json')
else:
filename = None
if test_name is None:
filename, _ = QFileDialog.getOpenFileName(self,
'Open Channels Montage',
filename,
'Channels File (*.json)')
else:
filename = test_name
if filename == '':
return
self.filename = filename
with open(filename, 'r') as outfile:
groups = load(outfile)
s_freq = self.parent.info.dataset.header['s_freq']
no_in_dataset = []
for one_grp in groups:
no_in_dataset.extend(set(one_grp['chan_to_plot']) -
set(chan_name))
chan_to_plot = set(chan_name) & set(one_grp['chan_to_plot'])
ref_chan = set(chan_name) & set(one_grp['ref_chan'])
group = ChannelsGroup(chan_name, one_grp['name'], one_grp, s_freq)
group.highlight_channels(group.idx_l0, chan_to_plot)
group.highlight_channels(group.idx_l1, ref_chan)
self.tabs.addTab(group, one_grp['name'])
if no_in_dataset:
msg = 'Channels not present in the dataset: ' + ', '.join(no_in_dataset)
self.parent.statusBar().showMessage(msg)
lg.debug(msg)
self.apply() | python | def load_channels(self, checked=False, test_name=None):
chan_name = self.parent.labels.chan_name
if self.filename is not None:
filename = self.filename
elif self.parent.info.filename is not None:
filename = (splitext(self.parent.info.filename)[0] +
'_channels.json')
else:
filename = None
if test_name is None:
filename, _ = QFileDialog.getOpenFileName(self,
'Open Channels Montage',
filename,
'Channels File (*.json)')
else:
filename = test_name
if filename == '':
return
self.filename = filename
with open(filename, 'r') as outfile:
groups = load(outfile)
s_freq = self.parent.info.dataset.header['s_freq']
no_in_dataset = []
for one_grp in groups:
no_in_dataset.extend(set(one_grp['chan_to_plot']) -
set(chan_name))
chan_to_plot = set(chan_name) & set(one_grp['chan_to_plot'])
ref_chan = set(chan_name) & set(one_grp['ref_chan'])
group = ChannelsGroup(chan_name, one_grp['name'], one_grp, s_freq)
group.highlight_channels(group.idx_l0, chan_to_plot)
group.highlight_channels(group.idx_l1, ref_chan)
self.tabs.addTab(group, one_grp['name'])
if no_in_dataset:
msg = 'Channels not present in the dataset: ' + ', '.join(no_in_dataset)
self.parent.statusBar().showMessage(msg)
lg.debug(msg)
self.apply() | [
"def",
"load_channels",
"(",
"self",
",",
"checked",
"=",
"False",
",",
"test_name",
"=",
"None",
")",
":",
"chan_name",
"=",
"self",
".",
"parent",
".",
"labels",
".",
"chan_name",
"if",
"self",
".",
"filename",
"is",
"not",
"None",
":",
"filename",
"... | Load channel groups from file.
Parameters
----------
test_name : path to file
when debugging the function, you can open a channels file from the
command line | [
"Load",
"channel",
"groups",
"from",
"file",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L450-L502 |
24,898 | wonambi-python/wonambi | wonambi/widgets/channels.py | Channels.save_channels | def save_channels(self, checked=False, test_name=None):
"""Save channel groups to file."""
self.read_group_info()
if self.filename is not None:
filename = self.filename
elif self.parent.info.filename is not None:
filename = (splitext(self.parent.info.filename)[0] +
'_channels.json')
else:
filename = None
if test_name is None:
filename, _ = QFileDialog.getSaveFileName(self,
'Save Channels Montage',
filename,
'Channels File (*.json)')
else:
filename = test_name
if filename == '':
return
self.filename = filename
groups = deepcopy(self.groups)
for one_grp in groups:
one_grp['color'] = one_grp['color'].rgba()
with open(filename, 'w') as outfile:
dump(groups, outfile, indent=' ') | python | def save_channels(self, checked=False, test_name=None):
self.read_group_info()
if self.filename is not None:
filename = self.filename
elif self.parent.info.filename is not None:
filename = (splitext(self.parent.info.filename)[0] +
'_channels.json')
else:
filename = None
if test_name is None:
filename, _ = QFileDialog.getSaveFileName(self,
'Save Channels Montage',
filename,
'Channels File (*.json)')
else:
filename = test_name
if filename == '':
return
self.filename = filename
groups = deepcopy(self.groups)
for one_grp in groups:
one_grp['color'] = one_grp['color'].rgba()
with open(filename, 'w') as outfile:
dump(groups, outfile, indent=' ') | [
"def",
"save_channels",
"(",
"self",
",",
"checked",
"=",
"False",
",",
"test_name",
"=",
"None",
")",
":",
"self",
".",
"read_group_info",
"(",
")",
"if",
"self",
".",
"filename",
"is",
"not",
"None",
":",
"filename",
"=",
"self",
".",
"filename",
"el... | Save channel groups to file. | [
"Save",
"channel",
"groups",
"to",
"file",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L504-L534 |
24,899 | wonambi-python/wonambi | wonambi/widgets/channels.py | Channels.reset | def reset(self):
"""Reset all the information of this widget."""
self.filename = None
self.groups = []
self.tabs.clear()
self.setEnabled(False)
self.button_color.setEnabled(False)
self.button_del.setEnabled(False)
self.button_apply.setEnabled(False)
self.action['load_channels'].setEnabled(False)
self.action['save_channels'].setEnabled(False) | python | def reset(self):
self.filename = None
self.groups = []
self.tabs.clear()
self.setEnabled(False)
self.button_color.setEnabled(False)
self.button_del.setEnabled(False)
self.button_apply.setEnabled(False)
self.action['load_channels'].setEnabled(False)
self.action['save_channels'].setEnabled(False) | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"filename",
"=",
"None",
"self",
".",
"groups",
"=",
"[",
"]",
"self",
".",
"tabs",
".",
"clear",
"(",
")",
"self",
".",
"setEnabled",
"(",
"False",
")",
"self",
".",
"button_color",
".",
"setEnab... | Reset all the information of this widget. | [
"Reset",
"all",
"the",
"information",
"of",
"this",
"widget",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L536-L548 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.