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
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
2,000
ampl/amplpy
amplpy/dataframe.py
DataFrame.setValues
def setValues(self, values): """ Set the values of a DataFrame from a dictionary. Args: values: Dictionary with the values to set. """ ncols = self.getNumCols() nindices = self.getNumIndices() for key, value in values.items(): key = Utils.convToList(key) assert len(key) == nindices value = Utils.convToList(value) assert len(value) == ncols-nindices self.addRow(key + value)
python
def setValues(self, values): """ Set the values of a DataFrame from a dictionary. Args: values: Dictionary with the values to set. """ ncols = self.getNumCols() nindices = self.getNumIndices() for key, value in values.items(): key = Utils.convToList(key) assert len(key) == nindices value = Utils.convToList(value) assert len(value) == ncols-nindices self.addRow(key + value)
[ "def", "setValues", "(", "self", ",", "values", ")", ":", "ncols", "=", "self", ".", "getNumCols", "(", ")", "nindices", "=", "self", ".", "getNumIndices", "(", ")", "for", "key", ",", "value", "in", "values", ".", "items", "(", ")", ":", "key", "=", "Utils", ".", "convToList", "(", "key", ")", "assert", "len", "(", "key", ")", "==", "nindices", "value", "=", "Utils", ".", "convToList", "(", "value", ")", "assert", "len", "(", "value", ")", "==", "ncols", "-", "nindices", "self", ".", "addRow", "(", "key", "+", "value", ")" ]
Set the values of a DataFrame from a dictionary. Args: values: Dictionary with the values to set.
[ "Set", "the", "values", "of", "a", "DataFrame", "from", "a", "dictionary", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L260-L274
2,001
ampl/amplpy
amplpy/dataframe.py
DataFrame.toDict
def toDict(self): """ Return a dictionary with the DataFrame data. """ d = {} nindices = self.getNumIndices() for i in range(self.getNumRows()): row = list(self.getRowByIndex(i)) if nindices > 1: key = tuple(row[:nindices]) elif nindices == 1: key = row[0] else: key = None if len(row) - nindices == 0: d[key] = None elif len(row) - nindices == 1: d[key] = row[nindices] else: d[key] = tuple(row[nindices:]) return d
python
def toDict(self): """ Return a dictionary with the DataFrame data. """ d = {} nindices = self.getNumIndices() for i in range(self.getNumRows()): row = list(self.getRowByIndex(i)) if nindices > 1: key = tuple(row[:nindices]) elif nindices == 1: key = row[0] else: key = None if len(row) - nindices == 0: d[key] = None elif len(row) - nindices == 1: d[key] = row[nindices] else: d[key] = tuple(row[nindices:]) return d
[ "def", "toDict", "(", "self", ")", ":", "d", "=", "{", "}", "nindices", "=", "self", ".", "getNumIndices", "(", ")", "for", "i", "in", "range", "(", "self", ".", "getNumRows", "(", ")", ")", ":", "row", "=", "list", "(", "self", ".", "getRowByIndex", "(", "i", ")", ")", "if", "nindices", ">", "1", ":", "key", "=", "tuple", "(", "row", "[", ":", "nindices", "]", ")", "elif", "nindices", "==", "1", ":", "key", "=", "row", "[", "0", "]", "else", ":", "key", "=", "None", "if", "len", "(", "row", ")", "-", "nindices", "==", "0", ":", "d", "[", "key", "]", "=", "None", "elif", "len", "(", "row", ")", "-", "nindices", "==", "1", ":", "d", "[", "key", "]", "=", "row", "[", "nindices", "]", "else", ":", "d", "[", "key", "]", "=", "tuple", "(", "row", "[", "nindices", ":", "]", ")", "return", "d" ]
Return a dictionary with the DataFrame data.
[ "Return", "a", "dictionary", "with", "the", "DataFrame", "data", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L276-L296
2,002
ampl/amplpy
amplpy/dataframe.py
DataFrame.toList
def toList(self): """ Return a list with the DataFrame data. """ if self.getNumCols() > 1: return [ tuple(self.getRowByIndex(i)) for i in range(self.getNumRows()) ] else: return [ self.getRowByIndex(i)[0] for i in range(self.getNumRows()) ]
python
def toList(self): """ Return a list with the DataFrame data. """ if self.getNumCols() > 1: return [ tuple(self.getRowByIndex(i)) for i in range(self.getNumRows()) ] else: return [ self.getRowByIndex(i)[0] for i in range(self.getNumRows()) ]
[ "def", "toList", "(", "self", ")", ":", "if", "self", ".", "getNumCols", "(", ")", ">", "1", ":", "return", "[", "tuple", "(", "self", ".", "getRowByIndex", "(", "i", ")", ")", "for", "i", "in", "range", "(", "self", ".", "getNumRows", "(", ")", ")", "]", "else", ":", "return", "[", "self", ".", "getRowByIndex", "(", "i", ")", "[", "0", "]", "for", "i", "in", "range", "(", "self", ".", "getNumRows", "(", ")", ")", "]" ]
Return a list with the DataFrame data.
[ "Return", "a", "list", "with", "the", "DataFrame", "data", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L298-L311
2,003
ampl/amplpy
amplpy/dataframe.py
DataFrame.toPandas
def toPandas(self): """ Return a pandas DataFrame with the DataFrame data. """ assert pd is not None nindices = self.getNumIndices() headers = self.getHeaders() columns = { header: list(self.getColumn(header)) for header in headers[nindices:] } index = zip(*[ list(self.getColumn(header)) for header in headers[:nindices] ]) index = [key if len(key) > 1 else key[0] for key in index] if index == []: return pd.DataFrame(columns, index=None) else: return pd.DataFrame(columns, index=index)
python
def toPandas(self): """ Return a pandas DataFrame with the DataFrame data. """ assert pd is not None nindices = self.getNumIndices() headers = self.getHeaders() columns = { header: list(self.getColumn(header)) for header in headers[nindices:] } index = zip(*[ list(self.getColumn(header)) for header in headers[:nindices] ]) index = [key if len(key) > 1 else key[0] for key in index] if index == []: return pd.DataFrame(columns, index=None) else: return pd.DataFrame(columns, index=index)
[ "def", "toPandas", "(", "self", ")", ":", "assert", "pd", "is", "not", "None", "nindices", "=", "self", ".", "getNumIndices", "(", ")", "headers", "=", "self", ".", "getHeaders", "(", ")", "columns", "=", "{", "header", ":", "list", "(", "self", ".", "getColumn", "(", "header", ")", ")", "for", "header", "in", "headers", "[", "nindices", ":", "]", "}", "index", "=", "zip", "(", "*", "[", "list", "(", "self", ".", "getColumn", "(", "header", ")", ")", "for", "header", "in", "headers", "[", ":", "nindices", "]", "]", ")", "index", "=", "[", "key", "if", "len", "(", "key", ")", ">", "1", "else", "key", "[", "0", "]", "for", "key", "in", "index", "]", "if", "index", "==", "[", "]", ":", "return", "pd", ".", "DataFrame", "(", "columns", ",", "index", "=", "None", ")", "else", ":", "return", "pd", ".", "DataFrame", "(", "columns", ",", "index", "=", "index", ")" ]
Return a pandas DataFrame with the DataFrame data.
[ "Return", "a", "pandas", "DataFrame", "with", "the", "DataFrame", "data", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L313-L332
2,004
ampl/amplpy
amplpy/parameter.py
Parameter.set
def set(self, *args): """ Set the value of a single instance of this parameter. Args: args: value if the parameter is scalar, index and value otherwise. Raises: RuntimeError: If the entity has been deleted in the underlying AMPL. TypeError: If the parameter is not scalar and the index is not provided. """ assert len(args) in (1, 2) if len(args) == 1: value = args[0] self._impl.set(value) else: index, value = args if isinstance(value, Real): self._impl.setTplDbl(Tuple(index)._impl, value) elif isinstance(value, basestring): self._impl.setTplStr(Tuple(index)._impl, value) else: raise TypeError
python
def set(self, *args): """ Set the value of a single instance of this parameter. Args: args: value if the parameter is scalar, index and value otherwise. Raises: RuntimeError: If the entity has been deleted in the underlying AMPL. TypeError: If the parameter is not scalar and the index is not provided. """ assert len(args) in (1, 2) if len(args) == 1: value = args[0] self._impl.set(value) else: index, value = args if isinstance(value, Real): self._impl.setTplDbl(Tuple(index)._impl, value) elif isinstance(value, basestring): self._impl.setTplStr(Tuple(index)._impl, value) else: raise TypeError
[ "def", "set", "(", "self", ",", "*", "args", ")", ":", "assert", "len", "(", "args", ")", "in", "(", "1", ",", "2", ")", "if", "len", "(", "args", ")", "==", "1", ":", "value", "=", "args", "[", "0", "]", "self", ".", "_impl", ".", "set", "(", "value", ")", "else", ":", "index", ",", "value", "=", "args", "if", "isinstance", "(", "value", ",", "Real", ")", ":", "self", ".", "_impl", ".", "setTplDbl", "(", "Tuple", "(", "index", ")", ".", "_impl", ",", "value", ")", "elif", "isinstance", "(", "value", ",", "basestring", ")", ":", "self", ".", "_impl", ".", "setTplStr", "(", "Tuple", "(", "index", ")", ".", "_impl", ",", "value", ")", "else", ":", "raise", "TypeError" ]
Set the value of a single instance of this parameter. Args: args: value if the parameter is scalar, index and value otherwise. Raises: RuntimeError: If the entity has been deleted in the underlying AMPL. TypeError: If the parameter is not scalar and the index is not provided.
[ "Set", "the", "value", "of", "a", "single", "instance", "of", "this", "parameter", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/parameter.py#L70-L96
2,005
ampl/amplpy
amplpy/set.py
Set.setValues
def setValues(self, values): """ Set the tuples in this set. Valid only for non-indexed sets. Args: values: A list of tuples or a :class:`~amplpy.DataFrame`. In the case of a :class:`~amplpy.DataFrame`, the number of indexing columns of the must be equal to the arity of the set. In the case of a list of tuples, the arity of each tuple must be equal to the arity of the set. For example, considering the following AMPL entities and corresponding Python objects: .. code-block:: ampl set A := 1..2; param p{i in A} := i+10; set AA; The following is valid: .. code-block:: python A, AA = ampl.getSet('A'), ampl.getSet('AA') AA.setValues(A.getValues()) # AA has now the members {1, 2} """ if isinstance(values, (list, set)): if any(isinstance(value, basestring) for value in values): values = list(map(str, values)) self._impl.setValuesStr(values, len(values)) elif all(isinstance(value, Real) for value in values): values = list(map(float, values)) self._impl.setValuesDbl(values, len(values)) elif all(isinstance(value, tuple) for value in values): self._impl.setValues(Utils.toTupleArray(values), len(values)) else: raise TypeError else: if np is not None and isinstance(values, np.ndarray): self.setValues(DataFrame.fromNumpy(values).toList()) return Entity.setValues(self, values)
python
def setValues(self, values): """ Set the tuples in this set. Valid only for non-indexed sets. Args: values: A list of tuples or a :class:`~amplpy.DataFrame`. In the case of a :class:`~amplpy.DataFrame`, the number of indexing columns of the must be equal to the arity of the set. In the case of a list of tuples, the arity of each tuple must be equal to the arity of the set. For example, considering the following AMPL entities and corresponding Python objects: .. code-block:: ampl set A := 1..2; param p{i in A} := i+10; set AA; The following is valid: .. code-block:: python A, AA = ampl.getSet('A'), ampl.getSet('AA') AA.setValues(A.getValues()) # AA has now the members {1, 2} """ if isinstance(values, (list, set)): if any(isinstance(value, basestring) for value in values): values = list(map(str, values)) self._impl.setValuesStr(values, len(values)) elif all(isinstance(value, Real) for value in values): values = list(map(float, values)) self._impl.setValuesDbl(values, len(values)) elif all(isinstance(value, tuple) for value in values): self._impl.setValues(Utils.toTupleArray(values), len(values)) else: raise TypeError else: if np is not None and isinstance(values, np.ndarray): self.setValues(DataFrame.fromNumpy(values).toList()) return Entity.setValues(self, values)
[ "def", "setValues", "(", "self", ",", "values", ")", ":", "if", "isinstance", "(", "values", ",", "(", "list", ",", "set", ")", ")", ":", "if", "any", "(", "isinstance", "(", "value", ",", "basestring", ")", "for", "value", "in", "values", ")", ":", "values", "=", "list", "(", "map", "(", "str", ",", "values", ")", ")", "self", ".", "_impl", ".", "setValuesStr", "(", "values", ",", "len", "(", "values", ")", ")", "elif", "all", "(", "isinstance", "(", "value", ",", "Real", ")", "for", "value", "in", "values", ")", ":", "values", "=", "list", "(", "map", "(", "float", ",", "values", ")", ")", "self", ".", "_impl", ".", "setValuesDbl", "(", "values", ",", "len", "(", "values", ")", ")", "elif", "all", "(", "isinstance", "(", "value", ",", "tuple", ")", "for", "value", "in", "values", ")", ":", "self", ".", "_impl", ".", "setValues", "(", "Utils", ".", "toTupleArray", "(", "values", ")", ",", "len", "(", "values", ")", ")", "else", ":", "raise", "TypeError", "else", ":", "if", "np", "is", "not", "None", "and", "isinstance", "(", "values", ",", "np", ".", "ndarray", ")", ":", "self", ".", "setValues", "(", "DataFrame", ".", "fromNumpy", "(", "values", ")", ".", "toList", "(", ")", ")", "return", "Entity", ".", "setValues", "(", "self", ",", "values", ")" ]
Set the tuples in this set. Valid only for non-indexed sets. Args: values: A list of tuples or a :class:`~amplpy.DataFrame`. In the case of a :class:`~amplpy.DataFrame`, the number of indexing columns of the must be equal to the arity of the set. In the case of a list of tuples, the arity of each tuple must be equal to the arity of the set. For example, considering the following AMPL entities and corresponding Python objects: .. code-block:: ampl set A := 1..2; param p{i in A} := i+10; set AA; The following is valid: .. code-block:: python A, AA = ampl.getSet('A'), ampl.getSet('AA') AA.setValues(A.getValues()) # AA has now the members {1, 2}
[ "Set", "the", "tuples", "in", "this", "set", ".", "Valid", "only", "for", "non", "-", "indexed", "sets", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/set.py#L80-L123
2,006
ampl/amplpy
amplpy/errorhandler.py
ErrorHandler.error
def error(self, amplexception): """ Receives notification of an error. """ msg = '\t'+str(amplexception).replace('\n', '\n\t') print('Error:\n{:s}'.format(msg)) raise amplexception
python
def error(self, amplexception): """ Receives notification of an error. """ msg = '\t'+str(amplexception).replace('\n', '\n\t') print('Error:\n{:s}'.format(msg)) raise amplexception
[ "def", "error", "(", "self", ",", "amplexception", ")", ":", "msg", "=", "'\\t'", "+", "str", "(", "amplexception", ")", ".", "replace", "(", "'\\n'", ",", "'\\n\\t'", ")", "print", "(", "'Error:\\n{:s}'", ".", "format", "(", "msg", ")", ")", "raise", "amplexception" ]
Receives notification of an error.
[ "Receives", "notification", "of", "an", "error", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/errorhandler.py#L18-L24
2,007
ampl/amplpy
amplpy/errorhandler.py
ErrorHandler.warning
def warning(self, amplexception): """ Receives notification of a warning. """ msg = '\t'+str(amplexception).replace('\n', '\n\t') print('Warning:\n{:s}'.format(msg))
python
def warning(self, amplexception): """ Receives notification of a warning. """ msg = '\t'+str(amplexception).replace('\n', '\n\t') print('Warning:\n{:s}'.format(msg))
[ "def", "warning", "(", "self", ",", "amplexception", ")", ":", "msg", "=", "'\\t'", "+", "str", "(", "amplexception", ")", ".", "replace", "(", "'\\n'", ",", "'\\n\\t'", ")", "print", "(", "'Warning:\\n{:s}'", ".", "format", "(", "msg", ")", ")" ]
Receives notification of a warning.
[ "Receives", "notification", "of", "a", "warning", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/errorhandler.py#L26-L31
2,008
ampl/amplpy
amplpy/utils.py
register_magics
def register_magics(store_name='_ampl_cells', ampl_object=None): """ Register jupyter notebook magics ``%%ampl`` and ``%%ampl_eval``. Args: store_name: Name of the store where ``%%ampl cells`` will be stored. ampl_object: Object used to evaluate ``%%ampl_eval`` cells. """ from IPython.core.magic import ( Magics, magics_class, cell_magic, line_magic ) @magics_class class StoreAMPL(Magics): def __init__(self, shell=None, **kwargs): Magics.__init__(self, shell=shell, **kwargs) self._store = [] shell.user_ns[store_name] = self._store @cell_magic def ampl(self, line, cell): """Store the cell in the store""" self._store.append(cell) @cell_magic def ampl_eval(self, line, cell): """Evaluate the cell""" ampl_object.eval(cell) @line_magic def get_ampl(self, line): """Retrieve the store""" return self._store get_ipython().register_magics(StoreAMPL)
python
def register_magics(store_name='_ampl_cells', ampl_object=None): """ Register jupyter notebook magics ``%%ampl`` and ``%%ampl_eval``. Args: store_name: Name of the store where ``%%ampl cells`` will be stored. ampl_object: Object used to evaluate ``%%ampl_eval`` cells. """ from IPython.core.magic import ( Magics, magics_class, cell_magic, line_magic ) @magics_class class StoreAMPL(Magics): def __init__(self, shell=None, **kwargs): Magics.__init__(self, shell=shell, **kwargs) self._store = [] shell.user_ns[store_name] = self._store @cell_magic def ampl(self, line, cell): """Store the cell in the store""" self._store.append(cell) @cell_magic def ampl_eval(self, line, cell): """Evaluate the cell""" ampl_object.eval(cell) @line_magic def get_ampl(self, line): """Retrieve the store""" return self._store get_ipython().register_magics(StoreAMPL)
[ "def", "register_magics", "(", "store_name", "=", "'_ampl_cells'", ",", "ampl_object", "=", "None", ")", ":", "from", "IPython", ".", "core", ".", "magic", "import", "(", "Magics", ",", "magics_class", ",", "cell_magic", ",", "line_magic", ")", "@", "magics_class", "class", "StoreAMPL", "(", "Magics", ")", ":", "def", "__init__", "(", "self", ",", "shell", "=", "None", ",", "*", "*", "kwargs", ")", ":", "Magics", ".", "__init__", "(", "self", ",", "shell", "=", "shell", ",", "*", "*", "kwargs", ")", "self", ".", "_store", "=", "[", "]", "shell", ".", "user_ns", "[", "store_name", "]", "=", "self", ".", "_store", "@", "cell_magic", "def", "ampl", "(", "self", ",", "line", ",", "cell", ")", ":", "\"\"\"Store the cell in the store\"\"\"", "self", ".", "_store", ".", "append", "(", "cell", ")", "@", "cell_magic", "def", "ampl_eval", "(", "self", ",", "line", ",", "cell", ")", ":", "\"\"\"Evaluate the cell\"\"\"", "ampl_object", ".", "eval", "(", "cell", ")", "@", "line_magic", "def", "get_ampl", "(", "self", ",", "line", ")", ":", "\"\"\"Retrieve the store\"\"\"", "return", "self", ".", "_store", "get_ipython", "(", ")", ".", "register_magics", "(", "StoreAMPL", ")" ]
Register jupyter notebook magics ``%%ampl`` and ``%%ampl_eval``. Args: store_name: Name of the store where ``%%ampl cells`` will be stored. ampl_object: Object used to evaluate ``%%ampl_eval`` cells.
[ "Register", "jupyter", "notebook", "magics", "%%ampl", "and", "%%ampl_eval", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/utils.py#L11-L45
2,009
ampl/amplpy
amplpy/variable.py
Variable.fix
def fix(self, value=None): """ Fix all instances of this variable to a value if provided or to their current value otherwise. Args: value: value to be set. """ if value is None: self._impl.fix() else: self._impl.fix(value)
python
def fix(self, value=None): """ Fix all instances of this variable to a value if provided or to their current value otherwise. Args: value: value to be set. """ if value is None: self._impl.fix() else: self._impl.fix(value)
[ "def", "fix", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "self", ".", "_impl", ".", "fix", "(", ")", "else", ":", "self", ".", "_impl", ".", "fix", "(", "value", ")" ]
Fix all instances of this variable to a value if provided or to their current value otherwise. Args: value: value to be set.
[ "Fix", "all", "instances", "of", "this", "variable", "to", "a", "value", "if", "provided", "or", "to", "their", "current", "value", "otherwise", "." ]
39df6954049a11a8f666aed26853259b4687099a
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/variable.py#L38-L50
2,010
eventable/vobject
vobject/base.py
toVName
def toVName(name, stripNum=0, upper=False): """ Turn a Python name into an iCalendar style name, optionally uppercase and with characters stripped off. """ if upper: name = name.upper() if stripNum != 0: name = name[:-stripNum] return name.replace('_', '-')
python
def toVName(name, stripNum=0, upper=False): """ Turn a Python name into an iCalendar style name, optionally uppercase and with characters stripped off. """ if upper: name = name.upper() if stripNum != 0: name = name[:-stripNum] return name.replace('_', '-')
[ "def", "toVName", "(", "name", ",", "stripNum", "=", "0", ",", "upper", "=", "False", ")", ":", "if", "upper", ":", "name", "=", "name", ".", "upper", "(", ")", "if", "stripNum", "!=", "0", ":", "name", "=", "name", "[", ":", "-", "stripNum", "]", "return", "name", ".", "replace", "(", "'_'", ",", "'-'", ")" ]
Turn a Python name into an iCalendar style name, optionally uppercase and with characters stripped off.
[ "Turn", "a", "Python", "name", "into", "an", "iCalendar", "style", "name", "optionally", "uppercase", "and", "with", "characters", "stripped", "off", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L261-L270
2,011
eventable/vobject
vobject/base.py
readComponents
def readComponents(streamOrString, validate=False, transform=True, ignoreUnreadable=False, allowQP=False): """ Generate one Component at a time from a stream. """ if isinstance(streamOrString, basestring): stream = six.StringIO(streamOrString) else: stream = streamOrString try: stack = Stack() versionLine = None n = 0 for line, n in getLogicalLines(stream, allowQP): if ignoreUnreadable: try: vline = textLineToContentLine(line, n) except VObjectError as e: if e.lineNumber is not None: msg = "Skipped line {lineNumber}, message: {msg}" else: msg = "Skipped a line, message: {msg}" logger.error(msg.format(**{'lineNumber': e.lineNumber, 'msg': str(e)})) continue else: vline = textLineToContentLine(line, n) if vline.name == "VERSION": versionLine = vline stack.modifyTop(vline) elif vline.name == "BEGIN": stack.push(Component(vline.value, group=vline.group)) elif vline.name == "PROFILE": if not stack.top(): stack.push(Component()) stack.top().setProfile(vline.value) elif vline.name == "END": if len(stack) == 0: err = "Attempted to end the {0} component but it was never opened" raise ParseError(err.format(vline.value), n) if vline.value.upper() == stack.topName(): # START matches END if len(stack) == 1: component = stack.pop() if versionLine is not None: component.setBehaviorFromVersionLine(versionLine) else: behavior = getBehavior(component.name) if behavior: component.setBehavior(behavior) if validate: component.validate(raiseException=True) if transform: component.transformChildrenToNative() yield component # EXIT POINT else: stack.modifyTop(stack.pop()) else: err = "{0} component wasn't closed" raise ParseError(err.format(stack.topName()), n) else: stack.modifyTop(vline) # not a START or END line if stack.top(): if stack.topName() is None: logger.warning("Top level component was never named") elif stack.top().useBegin: raise ParseError("Component {0!s} was never closed".format( (stack.topName())), n) yield stack.pop() except ParseError as e: e.input = streamOrString raise
python
def readComponents(streamOrString, validate=False, transform=True, ignoreUnreadable=False, allowQP=False): """ Generate one Component at a time from a stream. """ if isinstance(streamOrString, basestring): stream = six.StringIO(streamOrString) else: stream = streamOrString try: stack = Stack() versionLine = None n = 0 for line, n in getLogicalLines(stream, allowQP): if ignoreUnreadable: try: vline = textLineToContentLine(line, n) except VObjectError as e: if e.lineNumber is not None: msg = "Skipped line {lineNumber}, message: {msg}" else: msg = "Skipped a line, message: {msg}" logger.error(msg.format(**{'lineNumber': e.lineNumber, 'msg': str(e)})) continue else: vline = textLineToContentLine(line, n) if vline.name == "VERSION": versionLine = vline stack.modifyTop(vline) elif vline.name == "BEGIN": stack.push(Component(vline.value, group=vline.group)) elif vline.name == "PROFILE": if not stack.top(): stack.push(Component()) stack.top().setProfile(vline.value) elif vline.name == "END": if len(stack) == 0: err = "Attempted to end the {0} component but it was never opened" raise ParseError(err.format(vline.value), n) if vline.value.upper() == stack.topName(): # START matches END if len(stack) == 1: component = stack.pop() if versionLine is not None: component.setBehaviorFromVersionLine(versionLine) else: behavior = getBehavior(component.name) if behavior: component.setBehavior(behavior) if validate: component.validate(raiseException=True) if transform: component.transformChildrenToNative() yield component # EXIT POINT else: stack.modifyTop(stack.pop()) else: err = "{0} component wasn't closed" raise ParseError(err.format(stack.topName()), n) else: stack.modifyTop(vline) # not a START or END line if stack.top(): if stack.topName() is None: logger.warning("Top level component was never named") elif stack.top().useBegin: raise ParseError("Component {0!s} was never closed".format( (stack.topName())), n) yield stack.pop() except ParseError as e: e.input = streamOrString raise
[ "def", "readComponents", "(", "streamOrString", ",", "validate", "=", "False", ",", "transform", "=", "True", ",", "ignoreUnreadable", "=", "False", ",", "allowQP", "=", "False", ")", ":", "if", "isinstance", "(", "streamOrString", ",", "basestring", ")", ":", "stream", "=", "six", ".", "StringIO", "(", "streamOrString", ")", "else", ":", "stream", "=", "streamOrString", "try", ":", "stack", "=", "Stack", "(", ")", "versionLine", "=", "None", "n", "=", "0", "for", "line", ",", "n", "in", "getLogicalLines", "(", "stream", ",", "allowQP", ")", ":", "if", "ignoreUnreadable", ":", "try", ":", "vline", "=", "textLineToContentLine", "(", "line", ",", "n", ")", "except", "VObjectError", "as", "e", ":", "if", "e", ".", "lineNumber", "is", "not", "None", ":", "msg", "=", "\"Skipped line {lineNumber}, message: {msg}\"", "else", ":", "msg", "=", "\"Skipped a line, message: {msg}\"", "logger", ".", "error", "(", "msg", ".", "format", "(", "*", "*", "{", "'lineNumber'", ":", "e", ".", "lineNumber", ",", "'msg'", ":", "str", "(", "e", ")", "}", ")", ")", "continue", "else", ":", "vline", "=", "textLineToContentLine", "(", "line", ",", "n", ")", "if", "vline", ".", "name", "==", "\"VERSION\"", ":", "versionLine", "=", "vline", "stack", ".", "modifyTop", "(", "vline", ")", "elif", "vline", ".", "name", "==", "\"BEGIN\"", ":", "stack", ".", "push", "(", "Component", "(", "vline", ".", "value", ",", "group", "=", "vline", ".", "group", ")", ")", "elif", "vline", ".", "name", "==", "\"PROFILE\"", ":", "if", "not", "stack", ".", "top", "(", ")", ":", "stack", ".", "push", "(", "Component", "(", ")", ")", "stack", ".", "top", "(", ")", ".", "setProfile", "(", "vline", ".", "value", ")", "elif", "vline", ".", "name", "==", "\"END\"", ":", "if", "len", "(", "stack", ")", "==", "0", ":", "err", "=", "\"Attempted to end the {0} component but it was never opened\"", "raise", "ParseError", "(", "err", ".", "format", "(", "vline", ".", "value", ")", ",", "n", ")", "if", "vline", ".", "value", ".", "upper", "(", ")", "==", "stack", ".", "topName", "(", ")", ":", "# START matches END", "if", "len", "(", "stack", ")", "==", "1", ":", "component", "=", "stack", ".", "pop", "(", ")", "if", "versionLine", "is", "not", "None", ":", "component", ".", "setBehaviorFromVersionLine", "(", "versionLine", ")", "else", ":", "behavior", "=", "getBehavior", "(", "component", ".", "name", ")", "if", "behavior", ":", "component", ".", "setBehavior", "(", "behavior", ")", "if", "validate", ":", "component", ".", "validate", "(", "raiseException", "=", "True", ")", "if", "transform", ":", "component", ".", "transformChildrenToNative", "(", ")", "yield", "component", "# EXIT POINT", "else", ":", "stack", ".", "modifyTop", "(", "stack", ".", "pop", "(", ")", ")", "else", ":", "err", "=", "\"{0} component wasn't closed\"", "raise", "ParseError", "(", "err", ".", "format", "(", "stack", ".", "topName", "(", ")", ")", ",", "n", ")", "else", ":", "stack", ".", "modifyTop", "(", "vline", ")", "# not a START or END line", "if", "stack", ".", "top", "(", ")", ":", "if", "stack", ".", "topName", "(", ")", "is", "None", ":", "logger", ".", "warning", "(", "\"Top level component was never named\"", ")", "elif", "stack", ".", "top", "(", ")", ".", "useBegin", ":", "raise", "ParseError", "(", "\"Component {0!s} was never closed\"", ".", "format", "(", "(", "stack", ".", "topName", "(", ")", ")", ")", ",", "n", ")", "yield", "stack", ".", "pop", "(", ")", "except", "ParseError", "as", "e", ":", "e", ".", "input", "=", "streamOrString", "raise" ]
Generate one Component at a time from a stream.
[ "Generate", "one", "Component", "at", "a", "time", "from", "a", "stream", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L1075-L1147
2,012
eventable/vobject
vobject/base.py
readOne
def readOne(stream, validate=False, transform=True, ignoreUnreadable=False, allowQP=False): """ Return the first component from stream. """ return next(readComponents(stream, validate, transform, ignoreUnreadable, allowQP))
python
def readOne(stream, validate=False, transform=True, ignoreUnreadable=False, allowQP=False): """ Return the first component from stream. """ return next(readComponents(stream, validate, transform, ignoreUnreadable, allowQP))
[ "def", "readOne", "(", "stream", ",", "validate", "=", "False", ",", "transform", "=", "True", ",", "ignoreUnreadable", "=", "False", ",", "allowQP", "=", "False", ")", ":", "return", "next", "(", "readComponents", "(", "stream", ",", "validate", ",", "transform", ",", "ignoreUnreadable", ",", "allowQP", ")", ")" ]
Return the first component from stream.
[ "Return", "the", "first", "component", "from", "stream", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L1150-L1156
2,013
eventable/vobject
vobject/base.py
registerBehavior
def registerBehavior(behavior, name=None, default=False, id=None): """ Register the given behavior. If default is True (or if this is the first version registered with this name), the version will be the default if no id is given. """ if not name: name = behavior.name.upper() if id is None: id = behavior.versionString if name in __behaviorRegistry: if default: __behaviorRegistry[name].insert(0, (id, behavior)) else: __behaviorRegistry[name].append((id, behavior)) else: __behaviorRegistry[name] = [(id, behavior)]
python
def registerBehavior(behavior, name=None, default=False, id=None): """ Register the given behavior. If default is True (or if this is the first version registered with this name), the version will be the default if no id is given. """ if not name: name = behavior.name.upper() if id is None: id = behavior.versionString if name in __behaviorRegistry: if default: __behaviorRegistry[name].insert(0, (id, behavior)) else: __behaviorRegistry[name].append((id, behavior)) else: __behaviorRegistry[name] = [(id, behavior)]
[ "def", "registerBehavior", "(", "behavior", ",", "name", "=", "None", ",", "default", "=", "False", ",", "id", "=", "None", ")", ":", "if", "not", "name", ":", "name", "=", "behavior", ".", "name", ".", "upper", "(", ")", "if", "id", "is", "None", ":", "id", "=", "behavior", ".", "versionString", "if", "name", "in", "__behaviorRegistry", ":", "if", "default", ":", "__behaviorRegistry", "[", "name", "]", ".", "insert", "(", "0", ",", "(", "id", ",", "behavior", ")", ")", "else", ":", "__behaviorRegistry", "[", "name", "]", ".", "append", "(", "(", "id", ",", "behavior", ")", ")", "else", ":", "__behaviorRegistry", "[", "name", "]", "=", "[", "(", "id", ",", "behavior", ")", "]" ]
Register the given behavior. If default is True (or if this is the first version registered with this name), the version will be the default if no id is given.
[ "Register", "the", "given", "behavior", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L1163-L1180
2,014
eventable/vobject
vobject/base.py
getBehavior
def getBehavior(name, id=None): """ Return a matching behavior if it exists, or None. If id is None, return the default for name. """ name = name.upper() if name in __behaviorRegistry: if id: for n, behavior in __behaviorRegistry[name]: if n == id: return behavior return __behaviorRegistry[name][0][1] return None
python
def getBehavior(name, id=None): """ Return a matching behavior if it exists, or None. If id is None, return the default for name. """ name = name.upper() if name in __behaviorRegistry: if id: for n, behavior in __behaviorRegistry[name]: if n == id: return behavior return __behaviorRegistry[name][0][1] return None
[ "def", "getBehavior", "(", "name", ",", "id", "=", "None", ")", ":", "name", "=", "name", ".", "upper", "(", ")", "if", "name", "in", "__behaviorRegistry", ":", "if", "id", ":", "for", "n", ",", "behavior", "in", "__behaviorRegistry", "[", "name", "]", ":", "if", "n", "==", "id", ":", "return", "behavior", "return", "__behaviorRegistry", "[", "name", "]", "[", "0", "]", "[", "1", "]", "return", "None" ]
Return a matching behavior if it exists, or None. If id is None, return the default for name.
[ "Return", "a", "matching", "behavior", "if", "it", "exists", "or", "None", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L1183-L1197
2,015
eventable/vobject
vobject/base.py
VBase.validate
def validate(self, *args, **kwds): """ Call the behavior's validate method, or return True. """ if self.behavior: return self.behavior.validate(self, *args, **kwds) return True
python
def validate(self, *args, **kwds): """ Call the behavior's validate method, or return True. """ if self.behavior: return self.behavior.validate(self, *args, **kwds) return True
[ "def", "validate", "(", "self", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "if", "self", ".", "behavior", ":", "return", "self", ".", "behavior", ".", "validate", "(", "self", ",", "*", "args", ",", "*", "*", "kwds", ")", "return", "True" ]
Call the behavior's validate method, or return True.
[ "Call", "the", "behavior", "s", "validate", "method", "or", "return", "True", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L119-L125
2,016
eventable/vobject
vobject/base.py
VBase.autoBehavior
def autoBehavior(self, cascade=False): """ Set behavior if name is in self.parentBehavior.knownChildren. If cascade is True, unset behavior and parentBehavior for all descendants, then recalculate behavior and parentBehavior. """ parentBehavior = self.parentBehavior if parentBehavior is not None: knownChildTup = parentBehavior.knownChildren.get(self.name, None) if knownChildTup is not None: behavior = getBehavior(self.name, knownChildTup[2]) if behavior is not None: self.setBehavior(behavior, cascade) if isinstance(self, ContentLine) and self.encoded: self.behavior.decode(self) elif isinstance(self, ContentLine): self.behavior = parentBehavior.defaultBehavior if self.encoded and self.behavior: self.behavior.decode(self)
python
def autoBehavior(self, cascade=False): """ Set behavior if name is in self.parentBehavior.knownChildren. If cascade is True, unset behavior and parentBehavior for all descendants, then recalculate behavior and parentBehavior. """ parentBehavior = self.parentBehavior if parentBehavior is not None: knownChildTup = parentBehavior.knownChildren.get(self.name, None) if knownChildTup is not None: behavior = getBehavior(self.name, knownChildTup[2]) if behavior is not None: self.setBehavior(behavior, cascade) if isinstance(self, ContentLine) and self.encoded: self.behavior.decode(self) elif isinstance(self, ContentLine): self.behavior = parentBehavior.defaultBehavior if self.encoded and self.behavior: self.behavior.decode(self)
[ "def", "autoBehavior", "(", "self", ",", "cascade", "=", "False", ")", ":", "parentBehavior", "=", "self", ".", "parentBehavior", "if", "parentBehavior", "is", "not", "None", ":", "knownChildTup", "=", "parentBehavior", ".", "knownChildren", ".", "get", "(", "self", ".", "name", ",", "None", ")", "if", "knownChildTup", "is", "not", "None", ":", "behavior", "=", "getBehavior", "(", "self", ".", "name", ",", "knownChildTup", "[", "2", "]", ")", "if", "behavior", "is", "not", "None", ":", "self", ".", "setBehavior", "(", "behavior", ",", "cascade", ")", "if", "isinstance", "(", "self", ",", "ContentLine", ")", "and", "self", ".", "encoded", ":", "self", ".", "behavior", ".", "decode", "(", "self", ")", "elif", "isinstance", "(", "self", ",", "ContentLine", ")", ":", "self", ".", "behavior", "=", "parentBehavior", ".", "defaultBehavior", "if", "self", ".", "encoded", "and", "self", ".", "behavior", ":", "self", ".", "behavior", ".", "decode", "(", "self", ")" ]
Set behavior if name is in self.parentBehavior.knownChildren. If cascade is True, unset behavior and parentBehavior for all descendants, then recalculate behavior and parentBehavior.
[ "Set", "behavior", "if", "name", "is", "in", "self", ".", "parentBehavior", ".", "knownChildren", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L141-L160
2,017
eventable/vobject
vobject/base.py
VBase.setBehavior
def setBehavior(self, behavior, cascade=True): """ Set behavior. If cascade is True, autoBehavior all descendants. """ self.behavior = behavior if cascade: for obj in self.getChildren(): obj.parentBehavior = behavior obj.autoBehavior(True)
python
def setBehavior(self, behavior, cascade=True): """ Set behavior. If cascade is True, autoBehavior all descendants. """ self.behavior = behavior if cascade: for obj in self.getChildren(): obj.parentBehavior = behavior obj.autoBehavior(True)
[ "def", "setBehavior", "(", "self", ",", "behavior", ",", "cascade", "=", "True", ")", ":", "self", ".", "behavior", "=", "behavior", "if", "cascade", ":", "for", "obj", "in", "self", ".", "getChildren", "(", ")", ":", "obj", ".", "parentBehavior", "=", "behavior", "obj", ".", "autoBehavior", "(", "True", ")" ]
Set behavior. If cascade is True, autoBehavior all descendants.
[ "Set", "behavior", ".", "If", "cascade", "is", "True", "autoBehavior", "all", "descendants", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L162-L170
2,018
eventable/vobject
vobject/base.py
VBase.serialize
def serialize(self, buf=None, lineLength=75, validate=True, behavior=None): """ Serialize to buf if it exists, otherwise return a string. Use self.behavior.serialize if behavior exists. """ if not behavior: behavior = self.behavior if behavior: if DEBUG: logger.debug("serializing {0!s} with behavior {1!s}".format(self.name, behavior)) return behavior.serialize(self, buf, lineLength, validate) else: if DEBUG: logger.debug("serializing {0!s} without behavior".format(self.name)) return defaultSerialize(self, buf, lineLength)
python
def serialize(self, buf=None, lineLength=75, validate=True, behavior=None): """ Serialize to buf if it exists, otherwise return a string. Use self.behavior.serialize if behavior exists. """ if not behavior: behavior = self.behavior if behavior: if DEBUG: logger.debug("serializing {0!s} with behavior {1!s}".format(self.name, behavior)) return behavior.serialize(self, buf, lineLength, validate) else: if DEBUG: logger.debug("serializing {0!s} without behavior".format(self.name)) return defaultSerialize(self, buf, lineLength)
[ "def", "serialize", "(", "self", ",", "buf", "=", "None", ",", "lineLength", "=", "75", ",", "validate", "=", "True", ",", "behavior", "=", "None", ")", ":", "if", "not", "behavior", ":", "behavior", "=", "self", ".", "behavior", "if", "behavior", ":", "if", "DEBUG", ":", "logger", ".", "debug", "(", "\"serializing {0!s} with behavior {1!s}\"", ".", "format", "(", "self", ".", "name", ",", "behavior", ")", ")", "return", "behavior", ".", "serialize", "(", "self", ",", "buf", ",", "lineLength", ",", "validate", ")", "else", ":", "if", "DEBUG", ":", "logger", ".", "debug", "(", "\"serializing {0!s} without behavior\"", ".", "format", "(", "self", ".", "name", ")", ")", "return", "defaultSerialize", "(", "self", ",", "buf", ",", "lineLength", ")" ]
Serialize to buf if it exists, otherwise return a string. Use self.behavior.serialize if behavior exists.
[ "Serialize", "to", "buf", "if", "it", "exists", "otherwise", "return", "a", "string", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L242-L258
2,019
eventable/vobject
vobject/base.py
ContentLine.valueRepr
def valueRepr(self): """ Transform the representation of the value according to the behavior, if any. """ v = self.value if self.behavior: v = self.behavior.valueRepr(self) return v
python
def valueRepr(self): """ Transform the representation of the value according to the behavior, if any. """ v = self.value if self.behavior: v = self.behavior.valueRepr(self) return v
[ "def", "valueRepr", "(", "self", ")", ":", "v", "=", "self", ".", "value", "if", "self", ".", "behavior", ":", "v", "=", "self", ".", "behavior", ".", "valueRepr", "(", "self", ")", "return", "v" ]
Transform the representation of the value according to the behavior, if any.
[ "Transform", "the", "representation", "of", "the", "value", "according", "to", "the", "behavior", "if", "any", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L419-L427
2,020
eventable/vobject
vobject/base.py
Component.setProfile
def setProfile(self, name): """ Assign a PROFILE to this unnamed component. Used by vCard, not by vCalendar. """ if self.name or self.useBegin: if self.name == name: return raise VObjectError("This component already has a PROFILE or " "uses BEGIN.") self.name = name.upper()
python
def setProfile(self, name): """ Assign a PROFILE to this unnamed component. Used by vCard, not by vCalendar. """ if self.name or self.useBegin: if self.name == name: return raise VObjectError("This component already has a PROFILE or " "uses BEGIN.") self.name = name.upper()
[ "def", "setProfile", "(", "self", ",", "name", ")", ":", "if", "self", ".", "name", "or", "self", ".", "useBegin", ":", "if", "self", ".", "name", "==", "name", ":", "return", "raise", "VObjectError", "(", "\"This component already has a PROFILE or \"", "\"uses BEGIN.\"", ")", "self", ".", "name", "=", "name", ".", "upper", "(", ")" ]
Assign a PROFILE to this unnamed component. Used by vCard, not by vCalendar.
[ "Assign", "a", "PROFILE", "to", "this", "unnamed", "component", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L501-L512
2,021
eventable/vobject
vobject/base.py
Component.add
def add(self, objOrName, group=None): """ Add objOrName to contents, set behavior if it can be inferred. If objOrName is a string, create an empty component or line based on behavior. If no behavior is found for the object, add a ContentLine. group is an optional prefix to the name of the object (see RFC 2425). """ if isinstance(objOrName, VBase): obj = objOrName if self.behavior: obj.parentBehavior = self.behavior obj.autoBehavior(True) else: name = objOrName.upper() try: id = self.behavior.knownChildren[name][2] behavior = getBehavior(name, id) if behavior.isComponent: obj = Component(name) else: obj = ContentLine(name, [], '', group) obj.parentBehavior = self.behavior obj.behavior = behavior obj = obj.transformToNative() except (KeyError, AttributeError): obj = ContentLine(objOrName, [], '', group) if obj.behavior is None and self.behavior is not None: if isinstance(obj, ContentLine): obj.behavior = self.behavior.defaultBehavior self.contents.setdefault(obj.name.lower(), []).append(obj) return obj
python
def add(self, objOrName, group=None): """ Add objOrName to contents, set behavior if it can be inferred. If objOrName is a string, create an empty component or line based on behavior. If no behavior is found for the object, add a ContentLine. group is an optional prefix to the name of the object (see RFC 2425). """ if isinstance(objOrName, VBase): obj = objOrName if self.behavior: obj.parentBehavior = self.behavior obj.autoBehavior(True) else: name = objOrName.upper() try: id = self.behavior.knownChildren[name][2] behavior = getBehavior(name, id) if behavior.isComponent: obj = Component(name) else: obj = ContentLine(name, [], '', group) obj.parentBehavior = self.behavior obj.behavior = behavior obj = obj.transformToNative() except (KeyError, AttributeError): obj = ContentLine(objOrName, [], '', group) if obj.behavior is None and self.behavior is not None: if isinstance(obj, ContentLine): obj.behavior = self.behavior.defaultBehavior self.contents.setdefault(obj.name.lower(), []).append(obj) return obj
[ "def", "add", "(", "self", ",", "objOrName", ",", "group", "=", "None", ")", ":", "if", "isinstance", "(", "objOrName", ",", "VBase", ")", ":", "obj", "=", "objOrName", "if", "self", ".", "behavior", ":", "obj", ".", "parentBehavior", "=", "self", ".", "behavior", "obj", ".", "autoBehavior", "(", "True", ")", "else", ":", "name", "=", "objOrName", ".", "upper", "(", ")", "try", ":", "id", "=", "self", ".", "behavior", ".", "knownChildren", "[", "name", "]", "[", "2", "]", "behavior", "=", "getBehavior", "(", "name", ",", "id", ")", "if", "behavior", ".", "isComponent", ":", "obj", "=", "Component", "(", "name", ")", "else", ":", "obj", "=", "ContentLine", "(", "name", ",", "[", "]", ",", "''", ",", "group", ")", "obj", ".", "parentBehavior", "=", "self", ".", "behavior", "obj", ".", "behavior", "=", "behavior", "obj", "=", "obj", ".", "transformToNative", "(", ")", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "obj", "=", "ContentLine", "(", "objOrName", ",", "[", "]", ",", "''", ",", "group", ")", "if", "obj", ".", "behavior", "is", "None", "and", "self", ".", "behavior", "is", "not", "None", ":", "if", "isinstance", "(", "obj", ",", "ContentLine", ")", ":", "obj", ".", "behavior", "=", "self", ".", "behavior", ".", "defaultBehavior", "self", ".", "contents", ".", "setdefault", "(", "obj", ".", "name", ".", "lower", "(", ")", ",", "[", "]", ")", ".", "append", "(", "obj", ")", "return", "obj" ]
Add objOrName to contents, set behavior if it can be inferred. If objOrName is a string, create an empty component or line based on behavior. If no behavior is found for the object, add a ContentLine. group is an optional prefix to the name of the object (see RFC 2425).
[ "Add", "objOrName", "to", "contents", "set", "behavior", "if", "it", "can", "be", "inferred", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L580-L612
2,022
eventable/vobject
vobject/base.py
Component.remove
def remove(self, obj): """ Remove obj from contents. """ named = self.contents.get(obj.name.lower()) if named: try: named.remove(obj) if len(named) == 0: del self.contents[obj.name.lower()] except ValueError: pass
python
def remove(self, obj): """ Remove obj from contents. """ named = self.contents.get(obj.name.lower()) if named: try: named.remove(obj) if len(named) == 0: del self.contents[obj.name.lower()] except ValueError: pass
[ "def", "remove", "(", "self", ",", "obj", ")", ":", "named", "=", "self", ".", "contents", ".", "get", "(", "obj", ".", "name", ".", "lower", "(", ")", ")", "if", "named", ":", "try", ":", "named", ".", "remove", "(", "obj", ")", "if", "len", "(", "named", ")", "==", "0", ":", "del", "self", ".", "contents", "[", "obj", ".", "name", ".", "lower", "(", ")", "]", "except", "ValueError", ":", "pass" ]
Remove obj from contents.
[ "Remove", "obj", "from", "contents", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L614-L625
2,023
eventable/vobject
vobject/base.py
Component.setBehaviorFromVersionLine
def setBehaviorFromVersionLine(self, versionLine): """ Set behavior if one matches name, versionLine.value. """ v = getBehavior(self.name, versionLine.value) if v: self.setBehavior(v)
python
def setBehaviorFromVersionLine(self, versionLine): """ Set behavior if one matches name, versionLine.value. """ v = getBehavior(self.name, versionLine.value) if v: self.setBehavior(v)
[ "def", "setBehaviorFromVersionLine", "(", "self", ",", "versionLine", ")", ":", "v", "=", "getBehavior", "(", "self", ".", "name", ",", "versionLine", ".", "value", ")", "if", "v", ":", "self", ".", "setBehavior", "(", "v", ")" ]
Set behavior if one matches name, versionLine.value.
[ "Set", "behavior", "if", "one", "matches", "name", "versionLine", ".", "value", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L657-L663
2,024
eventable/vobject
vobject/base.py
Component.transformChildrenToNative
def transformChildrenToNative(self): """ Recursively replace children with their native representation. Sort to get dependency order right, like vtimezone before vevent. """ for childArray in (self.contents[k] for k in self.sortChildKeys()): for child in childArray: child = child.transformToNative() child.transformChildrenToNative()
python
def transformChildrenToNative(self): """ Recursively replace children with their native representation. Sort to get dependency order right, like vtimezone before vevent. """ for childArray in (self.contents[k] for k in self.sortChildKeys()): for child in childArray: child = child.transformToNative() child.transformChildrenToNative()
[ "def", "transformChildrenToNative", "(", "self", ")", ":", "for", "childArray", "in", "(", "self", ".", "contents", "[", "k", "]", "for", "k", "in", "self", ".", "sortChildKeys", "(", ")", ")", ":", "for", "child", "in", "childArray", ":", "child", "=", "child", ".", "transformToNative", "(", ")", "child", ".", "transformChildrenToNative", "(", ")" ]
Recursively replace children with their native representation. Sort to get dependency order right, like vtimezone before vevent.
[ "Recursively", "replace", "children", "with", "their", "native", "representation", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L665-L674
2,025
eventable/vobject
vobject/base.py
Component.transformChildrenFromNative
def transformChildrenFromNative(self, clearBehavior=True): """ Recursively transform native children to vanilla representations. """ for childArray in self.contents.values(): for child in childArray: child = child.transformFromNative() child.transformChildrenFromNative(clearBehavior) if clearBehavior: child.behavior = None child.parentBehavior = None
python
def transformChildrenFromNative(self, clearBehavior=True): """ Recursively transform native children to vanilla representations. """ for childArray in self.contents.values(): for child in childArray: child = child.transformFromNative() child.transformChildrenFromNative(clearBehavior) if clearBehavior: child.behavior = None child.parentBehavior = None
[ "def", "transformChildrenFromNative", "(", "self", ",", "clearBehavior", "=", "True", ")", ":", "for", "childArray", "in", "self", ".", "contents", ".", "values", "(", ")", ":", "for", "child", "in", "childArray", ":", "child", "=", "child", ".", "transformFromNative", "(", ")", "child", ".", "transformChildrenFromNative", "(", "clearBehavior", ")", "if", "clearBehavior", ":", "child", ".", "behavior", "=", "None", "child", ".", "parentBehavior", "=", "None" ]
Recursively transform native children to vanilla representations.
[ "Recursively", "transform", "native", "children", "to", "vanilla", "representations", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L676-L686
2,026
eventable/vobject
docs/build/lib/vobject/change_tz.py
change_tz
def change_tz(cal, new_timezone, default, utc_only=False, utc_tz=icalendar.utc): """ Change the timezone of the specified component. Args: cal (Component): the component to change new_timezone (tzinfo): the timezone to change to default (tzinfo): a timezone to assume if the dtstart or dtend in cal doesn't have an existing timezone utc_only (bool): only convert dates that are in utc utc_tz (tzinfo): the tzinfo to compare to for UTC when processing utc_only=True """ for vevent in getattr(cal, 'vevent_list', []): start = getattr(vevent, 'dtstart', None) end = getattr(vevent, 'dtend', None) for node in (start, end): if node: dt = node.value if (isinstance(dt, datetime) and (not utc_only or dt.tzinfo == utc_tz)): if dt.tzinfo is None: dt = dt.replace(tzinfo = default) node.value = dt.astimezone(new_timezone)
python
def change_tz(cal, new_timezone, default, utc_only=False, utc_tz=icalendar.utc): """ Change the timezone of the specified component. Args: cal (Component): the component to change new_timezone (tzinfo): the timezone to change to default (tzinfo): a timezone to assume if the dtstart or dtend in cal doesn't have an existing timezone utc_only (bool): only convert dates that are in utc utc_tz (tzinfo): the tzinfo to compare to for UTC when processing utc_only=True """ for vevent in getattr(cal, 'vevent_list', []): start = getattr(vevent, 'dtstart', None) end = getattr(vevent, 'dtend', None) for node in (start, end): if node: dt = node.value if (isinstance(dt, datetime) and (not utc_only or dt.tzinfo == utc_tz)): if dt.tzinfo is None: dt = dt.replace(tzinfo = default) node.value = dt.astimezone(new_timezone)
[ "def", "change_tz", "(", "cal", ",", "new_timezone", ",", "default", ",", "utc_only", "=", "False", ",", "utc_tz", "=", "icalendar", ".", "utc", ")", ":", "for", "vevent", "in", "getattr", "(", "cal", ",", "'vevent_list'", ",", "[", "]", ")", ":", "start", "=", "getattr", "(", "vevent", ",", "'dtstart'", ",", "None", ")", "end", "=", "getattr", "(", "vevent", ",", "'dtend'", ",", "None", ")", "for", "node", "in", "(", "start", ",", "end", ")", ":", "if", "node", ":", "dt", "=", "node", ".", "value", "if", "(", "isinstance", "(", "dt", ",", "datetime", ")", "and", "(", "not", "utc_only", "or", "dt", ".", "tzinfo", "==", "utc_tz", ")", ")", ":", "if", "dt", ".", "tzinfo", "is", "None", ":", "dt", "=", "dt", ".", "replace", "(", "tzinfo", "=", "default", ")", "node", ".", "value", "=", "dt", ".", "astimezone", "(", "new_timezone", ")" ]
Change the timezone of the specified component. Args: cal (Component): the component to change new_timezone (tzinfo): the timezone to change to default (tzinfo): a timezone to assume if the dtstart or dtend in cal doesn't have an existing timezone utc_only (bool): only convert dates that are in utc utc_tz (tzinfo): the tzinfo to compare to for UTC when processing utc_only=True
[ "Change", "the", "timezone", "of", "the", "specified", "component", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/change_tz.py#L13-L37
2,027
eventable/vobject
docs/build/lib/vobject/base.py
defaultSerialize
def defaultSerialize(obj, buf, lineLength): """ Encode and fold obj and its children, write to buf or return a string. """ outbuf = buf or six.StringIO() if isinstance(obj, Component): if obj.group is None: groupString = '' else: groupString = obj.group + '.' if obj.useBegin: foldOneLine(outbuf, "{0}BEGIN:{1}".format(groupString, obj.name), lineLength) for child in obj.getSortedChildren(): # validate is recursive, we only need to validate once child.serialize(outbuf, lineLength, validate=False) if obj.useBegin: foldOneLine(outbuf, "{0}END:{1}".format(groupString, obj.name), lineLength) elif isinstance(obj, ContentLine): startedEncoded = obj.encoded if obj.behavior and not startedEncoded: obj.behavior.encode(obj) s = six.StringIO() if obj.group is not None: s.write(obj.group + '.') s.write(obj.name.upper()) keys = sorted(obj.params.keys()) for key in keys: paramstr = ','.join(dquoteEscape(p) for p in obj.params[key]) s.write(";{0}={1}".format(key, paramstr)) s.write(":{0}".format(str_(obj.value))) if obj.behavior and not startedEncoded: obj.behavior.decode(obj) foldOneLine(outbuf, s.getvalue(), lineLength) return buf or outbuf.getvalue()
python
def defaultSerialize(obj, buf, lineLength): """ Encode and fold obj and its children, write to buf or return a string. """ outbuf = buf or six.StringIO() if isinstance(obj, Component): if obj.group is None: groupString = '' else: groupString = obj.group + '.' if obj.useBegin: foldOneLine(outbuf, "{0}BEGIN:{1}".format(groupString, obj.name), lineLength) for child in obj.getSortedChildren(): # validate is recursive, we only need to validate once child.serialize(outbuf, lineLength, validate=False) if obj.useBegin: foldOneLine(outbuf, "{0}END:{1}".format(groupString, obj.name), lineLength) elif isinstance(obj, ContentLine): startedEncoded = obj.encoded if obj.behavior and not startedEncoded: obj.behavior.encode(obj) s = six.StringIO() if obj.group is not None: s.write(obj.group + '.') s.write(obj.name.upper()) keys = sorted(obj.params.keys()) for key in keys: paramstr = ','.join(dquoteEscape(p) for p in obj.params[key]) s.write(";{0}={1}".format(key, paramstr)) s.write(":{0}".format(str_(obj.value))) if obj.behavior and not startedEncoded: obj.behavior.decode(obj) foldOneLine(outbuf, s.getvalue(), lineLength) return buf or outbuf.getvalue()
[ "def", "defaultSerialize", "(", "obj", ",", "buf", ",", "lineLength", ")", ":", "outbuf", "=", "buf", "or", "six", ".", "StringIO", "(", ")", "if", "isinstance", "(", "obj", ",", "Component", ")", ":", "if", "obj", ".", "group", "is", "None", ":", "groupString", "=", "''", "else", ":", "groupString", "=", "obj", ".", "group", "+", "'.'", "if", "obj", ".", "useBegin", ":", "foldOneLine", "(", "outbuf", ",", "\"{0}BEGIN:{1}\"", ".", "format", "(", "groupString", ",", "obj", ".", "name", ")", ",", "lineLength", ")", "for", "child", "in", "obj", ".", "getSortedChildren", "(", ")", ":", "# validate is recursive, we only need to validate once", "child", ".", "serialize", "(", "outbuf", ",", "lineLength", ",", "validate", "=", "False", ")", "if", "obj", ".", "useBegin", ":", "foldOneLine", "(", "outbuf", ",", "\"{0}END:{1}\"", ".", "format", "(", "groupString", ",", "obj", ".", "name", ")", ",", "lineLength", ")", "elif", "isinstance", "(", "obj", ",", "ContentLine", ")", ":", "startedEncoded", "=", "obj", ".", "encoded", "if", "obj", ".", "behavior", "and", "not", "startedEncoded", ":", "obj", ".", "behavior", ".", "encode", "(", "obj", ")", "s", "=", "six", ".", "StringIO", "(", ")", "if", "obj", ".", "group", "is", "not", "None", ":", "s", ".", "write", "(", "obj", ".", "group", "+", "'.'", ")", "s", ".", "write", "(", "obj", ".", "name", ".", "upper", "(", ")", ")", "keys", "=", "sorted", "(", "obj", ".", "params", ".", "keys", "(", ")", ")", "for", "key", "in", "keys", ":", "paramstr", "=", "','", ".", "join", "(", "dquoteEscape", "(", "p", ")", "for", "p", "in", "obj", ".", "params", "[", "key", "]", ")", "s", ".", "write", "(", "\";{0}={1}\"", ".", "format", "(", "key", ",", "paramstr", ")", ")", "s", ".", "write", "(", "\":{0}\"", ".", "format", "(", "str_", "(", "obj", ".", "value", ")", ")", ")", "if", "obj", ".", "behavior", "and", "not", "startedEncoded", ":", "obj", ".", "behavior", ".", "decode", "(", "obj", ")", "foldOneLine", "(", "outbuf", ",", "s", ".", "getvalue", "(", ")", ",", "lineLength", ")", "return", "buf", "or", "outbuf", ".", "getvalue", "(", ")" ]
Encode and fold obj and its children, write to buf or return a string.
[ "Encode", "and", "fold", "obj", "and", "its", "children", "write", "to", "buf", "or", "return", "a", "string", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/base.py#L977-L1017
2,028
eventable/vobject
docs/build/lib/vobject/icalendar.py
toUnicode
def toUnicode(s): """ Take a string or unicode, turn it into unicode, decoding as utf-8 """ if isinstance(s, six.binary_type): s = s.decode('utf-8') return s
python
def toUnicode(s): """ Take a string or unicode, turn it into unicode, decoding as utf-8 """ if isinstance(s, six.binary_type): s = s.decode('utf-8') return s
[ "def", "toUnicode", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "six", ".", "binary_type", ")", ":", "s", "=", "s", ".", "decode", "(", "'utf-8'", ")", "return", "s" ]
Take a string or unicode, turn it into unicode, decoding as utf-8
[ "Take", "a", "string", "or", "unicode", "turn", "it", "into", "unicode", "decoding", "as", "utf", "-", "8" ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L54-L60
2,029
eventable/vobject
docs/build/lib/vobject/icalendar.py
numToDigits
def numToDigits(num, places): """ Helper, for converting numbers to textual digits. """ s = str(num) if len(s) < places: return ("0" * (places - len(s))) + s elif len(s) > places: return s[len(s)-places: ] else: return s
python
def numToDigits(num, places): """ Helper, for converting numbers to textual digits. """ s = str(num) if len(s) < places: return ("0" * (places - len(s))) + s elif len(s) > places: return s[len(s)-places: ] else: return s
[ "def", "numToDigits", "(", "num", ",", "places", ")", ":", "s", "=", "str", "(", "num", ")", "if", "len", "(", "s", ")", "<", "places", ":", "return", "(", "\"0\"", "*", "(", "places", "-", "len", "(", "s", ")", ")", ")", "+", "s", "elif", "len", "(", "s", ")", ">", "places", ":", "return", "s", "[", "len", "(", "s", ")", "-", "places", ":", "]", "else", ":", "return", "s" ]
Helper, for converting numbers to textual digits.
[ "Helper", "for", "converting", "numbers", "to", "textual", "digits", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1503-L1513
2,030
eventable/vobject
docs/build/lib/vobject/icalendar.py
timedeltaToString
def timedeltaToString(delta): """ Convert timedelta to an ical DURATION. """ if delta.days == 0: sign = 1 else: sign = delta.days / abs(delta.days) delta = abs(delta) days = delta.days hours = int(delta.seconds / 3600) minutes = int((delta.seconds % 3600) / 60) seconds = int(delta.seconds % 60) output = '' if sign == -1: output += '-' output += 'P' if days: output += '{}D'.format(days) if hours or minutes or seconds: output += 'T' elif not days: # Deal with zero duration output += 'T0S' if hours: output += '{}H'.format(hours) if minutes: output += '{}M'.format(minutes) if seconds: output += '{}S'.format(seconds) return output
python
def timedeltaToString(delta): """ Convert timedelta to an ical DURATION. """ if delta.days == 0: sign = 1 else: sign = delta.days / abs(delta.days) delta = abs(delta) days = delta.days hours = int(delta.seconds / 3600) minutes = int((delta.seconds % 3600) / 60) seconds = int(delta.seconds % 60) output = '' if sign == -1: output += '-' output += 'P' if days: output += '{}D'.format(days) if hours or minutes or seconds: output += 'T' elif not days: # Deal with zero duration output += 'T0S' if hours: output += '{}H'.format(hours) if minutes: output += '{}M'.format(minutes) if seconds: output += '{}S'.format(seconds) return output
[ "def", "timedeltaToString", "(", "delta", ")", ":", "if", "delta", ".", "days", "==", "0", ":", "sign", "=", "1", "else", ":", "sign", "=", "delta", ".", "days", "/", "abs", "(", "delta", ".", "days", ")", "delta", "=", "abs", "(", "delta", ")", "days", "=", "delta", ".", "days", "hours", "=", "int", "(", "delta", ".", "seconds", "/", "3600", ")", "minutes", "=", "int", "(", "(", "delta", ".", "seconds", "%", "3600", ")", "/", "60", ")", "seconds", "=", "int", "(", "delta", ".", "seconds", "%", "60", ")", "output", "=", "''", "if", "sign", "==", "-", "1", ":", "output", "+=", "'-'", "output", "+=", "'P'", "if", "days", ":", "output", "+=", "'{}D'", ".", "format", "(", "days", ")", "if", "hours", "or", "minutes", "or", "seconds", ":", "output", "+=", "'T'", "elif", "not", "days", ":", "# Deal with zero duration", "output", "+=", "'T0S'", "if", "hours", ":", "output", "+=", "'{}H'", ".", "format", "(", "hours", ")", "if", "minutes", ":", "output", "+=", "'{}M'", ".", "format", "(", "minutes", ")", "if", "seconds", ":", "output", "+=", "'{}S'", ".", "format", "(", "seconds", ")", "return", "output" ]
Convert timedelta to an ical DURATION.
[ "Convert", "timedelta", "to", "an", "ical", "DURATION", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1515-L1545
2,031
eventable/vobject
docs/build/lib/vobject/icalendar.py
stringToTextValues
def stringToTextValues(s, listSeparator=',', charList=None, strict=False): """ Returns list of strings. """ if charList is None: charList = escapableCharList def escapableChar (c): return c in charList def error(msg): if strict: raise ParseError(msg) else: logging.error(msg) # vars which control state machine charIterator = enumerate(s) state = "read normal" current = [] results = [] while True: try: charIndex, char = next(charIterator) except: char = "eof" if state == "read normal": if char == '\\': state = "read escaped char" elif char == listSeparator: state = "read normal" current = "".join(current) results.append(current) current = [] elif char == "eof": state = "end" else: state = "read normal" current.append(char) elif state == "read escaped char": if escapableChar(char): state = "read normal" if char in 'nN': current.append('\n') else: current.append(char) else: state = "read normal" # leave unrecognized escaped characters for later passes current.append('\\' + char) elif state == "end": # an end state if len(current) or len(results) == 0: current = "".join(current) results.append(current) return results elif state == "error": # an end state return results else: state = "error" error("unknown state: '{0!s}' reached in {1!s}".format(state, s))
python
def stringToTextValues(s, listSeparator=',', charList=None, strict=False): """ Returns list of strings. """ if charList is None: charList = escapableCharList def escapableChar (c): return c in charList def error(msg): if strict: raise ParseError(msg) else: logging.error(msg) # vars which control state machine charIterator = enumerate(s) state = "read normal" current = [] results = [] while True: try: charIndex, char = next(charIterator) except: char = "eof" if state == "read normal": if char == '\\': state = "read escaped char" elif char == listSeparator: state = "read normal" current = "".join(current) results.append(current) current = [] elif char == "eof": state = "end" else: state = "read normal" current.append(char) elif state == "read escaped char": if escapableChar(char): state = "read normal" if char in 'nN': current.append('\n') else: current.append(char) else: state = "read normal" # leave unrecognized escaped characters for later passes current.append('\\' + char) elif state == "end": # an end state if len(current) or len(results) == 0: current = "".join(current) results.append(current) return results elif state == "error": # an end state return results else: state = "error" error("unknown state: '{0!s}' reached in {1!s}".format(state, s))
[ "def", "stringToTextValues", "(", "s", ",", "listSeparator", "=", "','", ",", "charList", "=", "None", ",", "strict", "=", "False", ")", ":", "if", "charList", "is", "None", ":", "charList", "=", "escapableCharList", "def", "escapableChar", "(", "c", ")", ":", "return", "c", "in", "charList", "def", "error", "(", "msg", ")", ":", "if", "strict", ":", "raise", "ParseError", "(", "msg", ")", "else", ":", "logging", ".", "error", "(", "msg", ")", "# vars which control state machine", "charIterator", "=", "enumerate", "(", "s", ")", "state", "=", "\"read normal\"", "current", "=", "[", "]", "results", "=", "[", "]", "while", "True", ":", "try", ":", "charIndex", ",", "char", "=", "next", "(", "charIterator", ")", "except", ":", "char", "=", "\"eof\"", "if", "state", "==", "\"read normal\"", ":", "if", "char", "==", "'\\\\'", ":", "state", "=", "\"read escaped char\"", "elif", "char", "==", "listSeparator", ":", "state", "=", "\"read normal\"", "current", "=", "\"\"", ".", "join", "(", "current", ")", "results", ".", "append", "(", "current", ")", "current", "=", "[", "]", "elif", "char", "==", "\"eof\"", ":", "state", "=", "\"end\"", "else", ":", "state", "=", "\"read normal\"", "current", ".", "append", "(", "char", ")", "elif", "state", "==", "\"read escaped char\"", ":", "if", "escapableChar", "(", "char", ")", ":", "state", "=", "\"read normal\"", "if", "char", "in", "'nN'", ":", "current", ".", "append", "(", "'\\n'", ")", "else", ":", "current", ".", "append", "(", "char", ")", "else", ":", "state", "=", "\"read normal\"", "# leave unrecognized escaped characters for later passes", "current", ".", "append", "(", "'\\\\'", "+", "char", ")", "elif", "state", "==", "\"end\"", ":", "# an end state", "if", "len", "(", "current", ")", "or", "len", "(", "results", ")", "==", "0", ":", "current", "=", "\"\"", ".", "join", "(", "current", ")", "results", ".", "append", "(", "current", ")", "return", "results", "elif", "state", "==", "\"error\"", ":", "# an end state", "return", "results", "else", ":", "state", "=", "\"error\"", "error", "(", "\"unknown state: '{0!s}' reached in {1!s}\"", ".", "format", "(", "state", ",", "s", ")", ")" ]
Returns list of strings.
[ "Returns", "list", "of", "strings", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1636-L1702
2,032
eventable/vobject
docs/build/lib/vobject/icalendar.py
parseDtstart
def parseDtstart(contentline, allowSignatureMismatch=False): """ Convert a contentline's value into a date or date-time. A variety of clients don't serialize dates with the appropriate VALUE parameter, so rather than failing on these (technically invalid) lines, if allowSignatureMismatch is True, try to parse both varieties. """ tzinfo = getTzid(getattr(contentline, 'tzid_param', None)) valueParam = getattr(contentline, 'value_param', 'DATE-TIME').upper() if valueParam == "DATE": return stringToDate(contentline.value) elif valueParam == "DATE-TIME": try: return stringToDateTime(contentline.value, tzinfo) except: if allowSignatureMismatch: return stringToDate(contentline.value) else: raise
python
def parseDtstart(contentline, allowSignatureMismatch=False): """ Convert a contentline's value into a date or date-time. A variety of clients don't serialize dates with the appropriate VALUE parameter, so rather than failing on these (technically invalid) lines, if allowSignatureMismatch is True, try to parse both varieties. """ tzinfo = getTzid(getattr(contentline, 'tzid_param', None)) valueParam = getattr(contentline, 'value_param', 'DATE-TIME').upper() if valueParam == "DATE": return stringToDate(contentline.value) elif valueParam == "DATE-TIME": try: return stringToDateTime(contentline.value, tzinfo) except: if allowSignatureMismatch: return stringToDate(contentline.value) else: raise
[ "def", "parseDtstart", "(", "contentline", ",", "allowSignatureMismatch", "=", "False", ")", ":", "tzinfo", "=", "getTzid", "(", "getattr", "(", "contentline", ",", "'tzid_param'", ",", "None", ")", ")", "valueParam", "=", "getattr", "(", "contentline", ",", "'value_param'", ",", "'DATE-TIME'", ")", ".", "upper", "(", ")", "if", "valueParam", "==", "\"DATE\"", ":", "return", "stringToDate", "(", "contentline", ".", "value", ")", "elif", "valueParam", "==", "\"DATE-TIME\"", ":", "try", ":", "return", "stringToDateTime", "(", "contentline", ".", "value", ",", "tzinfo", ")", "except", ":", "if", "allowSignatureMismatch", ":", "return", "stringToDate", "(", "contentline", ".", "value", ")", "else", ":", "raise" ]
Convert a contentline's value into a date or date-time. A variety of clients don't serialize dates with the appropriate VALUE parameter, so rather than failing on these (technically invalid) lines, if allowSignatureMismatch is True, try to parse both varieties.
[ "Convert", "a", "contentline", "s", "value", "into", "a", "date", "or", "date", "-", "time", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1823-L1842
2,033
eventable/vobject
docs/build/lib/vobject/icalendar.py
tzinfo_eq
def tzinfo_eq(tzinfo1, tzinfo2, startYear = 2000, endYear=2020): """ Compare offsets and DST transitions from startYear to endYear. """ if tzinfo1 == tzinfo2: return True elif tzinfo1 is None or tzinfo2 is None: return False def dt_test(dt): if dt is None: return True return tzinfo1.utcoffset(dt) == tzinfo2.utcoffset(dt) if not dt_test(datetime.datetime(startYear, 1, 1)): return False for year in range(startYear, endYear): for transitionTo in 'daylight', 'standard': t1=getTransition(transitionTo, year, tzinfo1) t2=getTransition(transitionTo, year, tzinfo2) if t1 != t2 or not dt_test(t1): return False return True
python
def tzinfo_eq(tzinfo1, tzinfo2, startYear = 2000, endYear=2020): """ Compare offsets and DST transitions from startYear to endYear. """ if tzinfo1 == tzinfo2: return True elif tzinfo1 is None or tzinfo2 is None: return False def dt_test(dt): if dt is None: return True return tzinfo1.utcoffset(dt) == tzinfo2.utcoffset(dt) if not dt_test(datetime.datetime(startYear, 1, 1)): return False for year in range(startYear, endYear): for transitionTo in 'daylight', 'standard': t1=getTransition(transitionTo, year, tzinfo1) t2=getTransition(transitionTo, year, tzinfo2) if t1 != t2 or not dt_test(t1): return False return True
[ "def", "tzinfo_eq", "(", "tzinfo1", ",", "tzinfo2", ",", "startYear", "=", "2000", ",", "endYear", "=", "2020", ")", ":", "if", "tzinfo1", "==", "tzinfo2", ":", "return", "True", "elif", "tzinfo1", "is", "None", "or", "tzinfo2", "is", "None", ":", "return", "False", "def", "dt_test", "(", "dt", ")", ":", "if", "dt", "is", "None", ":", "return", "True", "return", "tzinfo1", ".", "utcoffset", "(", "dt", ")", "==", "tzinfo2", ".", "utcoffset", "(", "dt", ")", "if", "not", "dt_test", "(", "datetime", ".", "datetime", "(", "startYear", ",", "1", ",", "1", ")", ")", ":", "return", "False", "for", "year", "in", "range", "(", "startYear", ",", "endYear", ")", ":", "for", "transitionTo", "in", "'daylight'", ",", "'standard'", ":", "t1", "=", "getTransition", "(", "transitionTo", ",", "year", ",", "tzinfo1", ")", "t2", "=", "getTransition", "(", "transitionTo", ",", "year", ",", "tzinfo2", ")", "if", "t1", "!=", "t2", "or", "not", "dt_test", "(", "t1", ")", ":", "return", "False", "return", "True" ]
Compare offsets and DST transitions from startYear to endYear.
[ "Compare", "offsets", "and", "DST", "transitions", "from", "startYear", "to", "endYear", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1929-L1951
2,034
eventable/vobject
docs/build/lib/vobject/icalendar.py
TimezoneComponent.registerTzinfo
def registerTzinfo(obj, tzinfo): """ Register tzinfo if it's not already registered, return its tzid. """ tzid = obj.pickTzid(tzinfo) if tzid and not getTzid(tzid, False): registerTzid(tzid, tzinfo) return tzid
python
def registerTzinfo(obj, tzinfo): """ Register tzinfo if it's not already registered, return its tzid. """ tzid = obj.pickTzid(tzinfo) if tzid and not getTzid(tzid, False): registerTzid(tzid, tzinfo) return tzid
[ "def", "registerTzinfo", "(", "obj", ",", "tzinfo", ")", ":", "tzid", "=", "obj", ".", "pickTzid", "(", "tzinfo", ")", "if", "tzid", "and", "not", "getTzid", "(", "tzid", ",", "False", ")", ":", "registerTzid", "(", "tzid", ",", "tzinfo", ")", "return", "tzid" ]
Register tzinfo if it's not already registered, return its tzid.
[ "Register", "tzinfo", "if", "it", "s", "not", "already", "registered", "return", "its", "tzid", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L121-L128
2,035
eventable/vobject
docs/build/lib/vobject/icalendar.py
TimezoneComponent.pickTzid
def pickTzid(tzinfo, allowUTC=False): """ Given a tzinfo class, use known APIs to determine TZID, or use tzname. """ if tzinfo is None or (not allowUTC and tzinfo_eq(tzinfo, utc)): # If tzinfo is UTC, we don't need a TZID return None # try PyICU's tzid key if hasattr(tzinfo, 'tzid'): return toUnicode(tzinfo.tzid) # try pytz zone key if hasattr(tzinfo, 'zone'): return toUnicode(tzinfo.zone) # try tzical's tzid key elif hasattr(tzinfo, '_tzid'): return toUnicode(tzinfo._tzid) else: # return tzname for standard (non-DST) time notDST = datetime.timedelta(0) for month in range(1, 13): dt = datetime.datetime(2000, month, 1) if tzinfo.dst(dt) == notDST: return toUnicode(tzinfo.tzname(dt)) # there was no standard time in 2000! raise VObjectError("Unable to guess TZID for tzinfo {0!s}" .format(tzinfo))
python
def pickTzid(tzinfo, allowUTC=False): """ Given a tzinfo class, use known APIs to determine TZID, or use tzname. """ if tzinfo is None or (not allowUTC and tzinfo_eq(tzinfo, utc)): # If tzinfo is UTC, we don't need a TZID return None # try PyICU's tzid key if hasattr(tzinfo, 'tzid'): return toUnicode(tzinfo.tzid) # try pytz zone key if hasattr(tzinfo, 'zone'): return toUnicode(tzinfo.zone) # try tzical's tzid key elif hasattr(tzinfo, '_tzid'): return toUnicode(tzinfo._tzid) else: # return tzname for standard (non-DST) time notDST = datetime.timedelta(0) for month in range(1, 13): dt = datetime.datetime(2000, month, 1) if tzinfo.dst(dt) == notDST: return toUnicode(tzinfo.tzname(dt)) # there was no standard time in 2000! raise VObjectError("Unable to guess TZID for tzinfo {0!s}" .format(tzinfo))
[ "def", "pickTzid", "(", "tzinfo", ",", "allowUTC", "=", "False", ")", ":", "if", "tzinfo", "is", "None", "or", "(", "not", "allowUTC", "and", "tzinfo_eq", "(", "tzinfo", ",", "utc", ")", ")", ":", "# If tzinfo is UTC, we don't need a TZID", "return", "None", "# try PyICU's tzid key", "if", "hasattr", "(", "tzinfo", ",", "'tzid'", ")", ":", "return", "toUnicode", "(", "tzinfo", ".", "tzid", ")", "# try pytz zone key", "if", "hasattr", "(", "tzinfo", ",", "'zone'", ")", ":", "return", "toUnicode", "(", "tzinfo", ".", "zone", ")", "# try tzical's tzid key", "elif", "hasattr", "(", "tzinfo", ",", "'_tzid'", ")", ":", "return", "toUnicode", "(", "tzinfo", ".", "_tzid", ")", "else", ":", "# return tzname for standard (non-DST) time", "notDST", "=", "datetime", ".", "timedelta", "(", "0", ")", "for", "month", "in", "range", "(", "1", ",", "13", ")", ":", "dt", "=", "datetime", ".", "datetime", "(", "2000", ",", "month", ",", "1", ")", "if", "tzinfo", ".", "dst", "(", "dt", ")", "==", "notDST", ":", "return", "toUnicode", "(", "tzinfo", ".", "tzname", "(", "dt", ")", ")", "# there was no standard time in 2000!", "raise", "VObjectError", "(", "\"Unable to guess TZID for tzinfo {0!s}\"", ".", "format", "(", "tzinfo", ")", ")" ]
Given a tzinfo class, use known APIs to determine TZID, or use tzname.
[ "Given", "a", "tzinfo", "class", "use", "known", "APIs", "to", "determine", "TZID", "or", "use", "tzname", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L325-L352
2,036
eventable/vobject
docs/build/lib/vobject/icalendar.py
RecurringBehavior.transformToNative
def transformToNative(obj): """ Turn a recurring Component into a RecurringComponent. """ if not obj.isNative: object.__setattr__(obj, '__class__', RecurringComponent) obj.isNative = True return obj
python
def transformToNative(obj): """ Turn a recurring Component into a RecurringComponent. """ if not obj.isNative: object.__setattr__(obj, '__class__', RecurringComponent) obj.isNative = True return obj
[ "def", "transformToNative", "(", "obj", ")", ":", "if", "not", "obj", ".", "isNative", ":", "object", ".", "__setattr__", "(", "obj", ",", "'__class__'", ",", "RecurringComponent", ")", "obj", ".", "isNative", "=", "True", "return", "obj" ]
Turn a recurring Component into a RecurringComponent.
[ "Turn", "a", "recurring", "Component", "into", "a", "RecurringComponent", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L667-L674
2,037
eventable/vobject
docs/build/lib/vobject/icalendar.py
RecurringBehavior.generateImplicitParameters
def generateImplicitParameters(obj): """ Generate a UID if one does not exist. This is just a dummy implementation, for now. """ if not hasattr(obj, 'uid'): rand = int(random.random() * 100000) now = datetime.datetime.now(utc) now = dateTimeToString(now) host = socket.gethostname() obj.add(ContentLine('UID', [], "{0} - {1}@{2}".format(now, rand, host)))
python
def generateImplicitParameters(obj): """ Generate a UID if one does not exist. This is just a dummy implementation, for now. """ if not hasattr(obj, 'uid'): rand = int(random.random() * 100000) now = datetime.datetime.now(utc) now = dateTimeToString(now) host = socket.gethostname() obj.add(ContentLine('UID', [], "{0} - {1}@{2}".format(now, rand, host)))
[ "def", "generateImplicitParameters", "(", "obj", ")", ":", "if", "not", "hasattr", "(", "obj", ",", "'uid'", ")", ":", "rand", "=", "int", "(", "random", ".", "random", "(", ")", "*", "100000", ")", "now", "=", "datetime", ".", "datetime", ".", "now", "(", "utc", ")", "now", "=", "dateTimeToString", "(", "now", ")", "host", "=", "socket", ".", "gethostname", "(", ")", "obj", ".", "add", "(", "ContentLine", "(", "'UID'", ",", "[", "]", ",", "\"{0} - {1}@{2}\"", ".", "format", "(", "now", ",", "rand", ",", "host", ")", ")", ")" ]
Generate a UID if one does not exist. This is just a dummy implementation, for now.
[ "Generate", "a", "UID", "if", "one", "does", "not", "exist", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L684-L696
2,038
eventable/vobject
docs/build/lib/vobject/icalendar.py
DateOrDateTimeBehavior.transformToNative
def transformToNative(obj): """ Turn obj.value into a date or datetime. """ if obj.isNative: return obj obj.isNative = True if obj.value == '': return obj obj.value=obj.value obj.value=parseDtstart(obj, allowSignatureMismatch=True) if getattr(obj, 'value_param', 'DATE-TIME').upper() == 'DATE-TIME': if hasattr(obj, 'tzid_param'): # Keep a copy of the original TZID around obj.params['X-VOBJ-ORIGINAL-TZID'] = [obj.tzid_param] del obj.tzid_param return obj
python
def transformToNative(obj): """ Turn obj.value into a date or datetime. """ if obj.isNative: return obj obj.isNative = True if obj.value == '': return obj obj.value=obj.value obj.value=parseDtstart(obj, allowSignatureMismatch=True) if getattr(obj, 'value_param', 'DATE-TIME').upper() == 'DATE-TIME': if hasattr(obj, 'tzid_param'): # Keep a copy of the original TZID around obj.params['X-VOBJ-ORIGINAL-TZID'] = [obj.tzid_param] del obj.tzid_param return obj
[ "def", "transformToNative", "(", "obj", ")", ":", "if", "obj", ".", "isNative", ":", "return", "obj", "obj", ".", "isNative", "=", "True", "if", "obj", ".", "value", "==", "''", ":", "return", "obj", "obj", ".", "value", "=", "obj", ".", "value", "obj", ".", "value", "=", "parseDtstart", "(", "obj", ",", "allowSignatureMismatch", "=", "True", ")", "if", "getattr", "(", "obj", ",", "'value_param'", ",", "'DATE-TIME'", ")", ".", "upper", "(", ")", "==", "'DATE-TIME'", ":", "if", "hasattr", "(", "obj", ",", "'tzid_param'", ")", ":", "# Keep a copy of the original TZID around", "obj", ".", "params", "[", "'X-VOBJ-ORIGINAL-TZID'", "]", "=", "[", "obj", ".", "tzid_param", "]", "del", "obj", ".", "tzid_param", "return", "obj" ]
Turn obj.value into a date or datetime.
[ "Turn", "obj", ".", "value", "into", "a", "date", "or", "datetime", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L762-L778
2,039
eventable/vobject
docs/build/lib/vobject/icalendar.py
DateOrDateTimeBehavior.transformFromNative
def transformFromNative(obj): """ Replace the date or datetime in obj.value with an ISO 8601 string. """ if type(obj.value) == datetime.date: obj.isNative = False obj.value_param = 'DATE' obj.value = dateToString(obj.value) return obj else: return DateTimeBehavior.transformFromNative(obj)
python
def transformFromNative(obj): """ Replace the date or datetime in obj.value with an ISO 8601 string. """ if type(obj.value) == datetime.date: obj.isNative = False obj.value_param = 'DATE' obj.value = dateToString(obj.value) return obj else: return DateTimeBehavior.transformFromNative(obj)
[ "def", "transformFromNative", "(", "obj", ")", ":", "if", "type", "(", "obj", ".", "value", ")", "==", "datetime", ".", "date", ":", "obj", ".", "isNative", "=", "False", "obj", ".", "value_param", "=", "'DATE'", "obj", ".", "value", "=", "dateToString", "(", "obj", ".", "value", ")", "return", "obj", "else", ":", "return", "DateTimeBehavior", ".", "transformFromNative", "(", "obj", ")" ]
Replace the date or datetime in obj.value with an ISO 8601 string.
[ "Replace", "the", "date", "or", "datetime", "in", "obj", ".", "value", "with", "an", "ISO", "8601", "string", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L781-L791
2,040
eventable/vobject
docs/build/lib/vobject/icalendar.py
MultiDateBehavior.transformFromNative
def transformFromNative(obj): """ Replace the date, datetime or period tuples in obj.value with appropriate strings. """ if obj.value and type(obj.value[0]) == datetime.date: obj.isNative = False obj.value_param = 'DATE' obj.value = ','.join([dateToString(val) for val in obj.value]) return obj # Fixme: handle PERIOD case else: if obj.isNative: obj.isNative = False transformed = [] tzid = None for val in obj.value: if tzid is None and type(val) == datetime.datetime: tzid = TimezoneComponent.registerTzinfo(val.tzinfo) if tzid is not None: obj.tzid_param = tzid transformed.append(dateTimeToString(val)) obj.value = ','.join(transformed) return obj
python
def transformFromNative(obj): """ Replace the date, datetime or period tuples in obj.value with appropriate strings. """ if obj.value and type(obj.value[0]) == datetime.date: obj.isNative = False obj.value_param = 'DATE' obj.value = ','.join([dateToString(val) for val in obj.value]) return obj # Fixme: handle PERIOD case else: if obj.isNative: obj.isNative = False transformed = [] tzid = None for val in obj.value: if tzid is None and type(val) == datetime.datetime: tzid = TimezoneComponent.registerTzinfo(val.tzinfo) if tzid is not None: obj.tzid_param = tzid transformed.append(dateTimeToString(val)) obj.value = ','.join(transformed) return obj
[ "def", "transformFromNative", "(", "obj", ")", ":", "if", "obj", ".", "value", "and", "type", "(", "obj", ".", "value", "[", "0", "]", ")", "==", "datetime", ".", "date", ":", "obj", ".", "isNative", "=", "False", "obj", ".", "value_param", "=", "'DATE'", "obj", ".", "value", "=", "','", ".", "join", "(", "[", "dateToString", "(", "val", ")", "for", "val", "in", "obj", ".", "value", "]", ")", "return", "obj", "# Fixme: handle PERIOD case", "else", ":", "if", "obj", ".", "isNative", ":", "obj", ".", "isNative", "=", "False", "transformed", "=", "[", "]", "tzid", "=", "None", "for", "val", "in", "obj", ".", "value", ":", "if", "tzid", "is", "None", "and", "type", "(", "val", ")", "==", "datetime", ".", "datetime", ":", "tzid", "=", "TimezoneComponent", ".", "registerTzinfo", "(", "val", ".", "tzinfo", ")", "if", "tzid", "is", "not", "None", ":", "obj", ".", "tzid_param", "=", "tzid", "transformed", ".", "append", "(", "dateTimeToString", "(", "val", ")", ")", "obj", ".", "value", "=", "','", ".", "join", "(", "transformed", ")", "return", "obj" ]
Replace the date, datetime or period tuples in obj.value with appropriate strings.
[ "Replace", "the", "date", "datetime", "or", "period", "tuples", "in", "obj", ".", "value", "with", "appropriate", "strings", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L825-L848
2,041
eventable/vobject
docs/build/lib/vobject/icalendar.py
MultiTextBehavior.decode
def decode(cls, line): """ Remove backslash escaping from line.value, then split on commas. """ if line.encoded: line.value = stringToTextValues(line.value, listSeparator=cls.listSeparator) line.encoded=False
python
def decode(cls, line): """ Remove backslash escaping from line.value, then split on commas. """ if line.encoded: line.value = stringToTextValues(line.value, listSeparator=cls.listSeparator) line.encoded=False
[ "def", "decode", "(", "cls", ",", "line", ")", ":", "if", "line", ".", "encoded", ":", "line", ".", "value", "=", "stringToTextValues", "(", "line", ".", "value", ",", "listSeparator", "=", "cls", ".", "listSeparator", ")", "line", ".", "encoded", "=", "False" ]
Remove backslash escaping from line.value, then split on commas.
[ "Remove", "backslash", "escaping", "from", "line", ".", "value", "then", "split", "on", "commas", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L860-L867
2,042
eventable/vobject
docs/build/lib/vobject/icalendar.py
VAlarm.generateImplicitParameters
def generateImplicitParameters(obj): """ Create default ACTION and TRIGGER if they're not set. """ try: obj.action except AttributeError: obj.add('action').value = 'AUDIO' try: obj.trigger except AttributeError: obj.add('trigger').value = datetime.timedelta(0)
python
def generateImplicitParameters(obj): """ Create default ACTION and TRIGGER if they're not set. """ try: obj.action except AttributeError: obj.add('action').value = 'AUDIO' try: obj.trigger except AttributeError: obj.add('trigger').value = datetime.timedelta(0)
[ "def", "generateImplicitParameters", "(", "obj", ")", ":", "try", ":", "obj", ".", "action", "except", "AttributeError", ":", "obj", ".", "add", "(", "'action'", ")", ".", "value", "=", "'AUDIO'", "try", ":", "obj", ".", "trigger", "except", "AttributeError", ":", "obj", ".", "add", "(", "'trigger'", ")", ".", "value", "=", "datetime", ".", "timedelta", "(", "0", ")" ]
Create default ACTION and TRIGGER if they're not set.
[ "Create", "default", "ACTION", "and", "TRIGGER", "if", "they", "re", "not", "set", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1208-L1219
2,043
eventable/vobject
docs/build/lib/vobject/icalendar.py
Duration.transformToNative
def transformToNative(obj): """ Turn obj.value into a datetime.timedelta. """ if obj.isNative: return obj obj.isNative = True obj.value=obj.value if obj.value == '': return obj else: deltalist=stringToDurations(obj.value) # When can DURATION have multiple durations? For now: if len(deltalist) == 1: obj.value = deltalist[0] return obj else: raise ParseError("DURATION must have a single duration string.")
python
def transformToNative(obj): """ Turn obj.value into a datetime.timedelta. """ if obj.isNative: return obj obj.isNative = True obj.value=obj.value if obj.value == '': return obj else: deltalist=stringToDurations(obj.value) # When can DURATION have multiple durations? For now: if len(deltalist) == 1: obj.value = deltalist[0] return obj else: raise ParseError("DURATION must have a single duration string.")
[ "def", "transformToNative", "(", "obj", ")", ":", "if", "obj", ".", "isNative", ":", "return", "obj", "obj", ".", "isNative", "=", "True", "obj", ".", "value", "=", "obj", ".", "value", "if", "obj", ".", "value", "==", "''", ":", "return", "obj", "else", ":", "deltalist", "=", "stringToDurations", "(", "obj", ".", "value", ")", "# When can DURATION have multiple durations? For now:", "if", "len", "(", "deltalist", ")", "==", "1", ":", "obj", ".", "value", "=", "deltalist", "[", "0", "]", "return", "obj", "else", ":", "raise", "ParseError", "(", "\"DURATION must have a single duration string.\"", ")" ]
Turn obj.value into a datetime.timedelta.
[ "Turn", "obj", ".", "value", "into", "a", "datetime", ".", "timedelta", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1332-L1349
2,044
eventable/vobject
docs/build/lib/vobject/icalendar.py
Duration.transformFromNative
def transformFromNative(obj): """ Replace the datetime.timedelta in obj.value with an RFC2445 string. """ if not obj.isNative: return obj obj.isNative = False obj.value = timedeltaToString(obj.value) return obj
python
def transformFromNative(obj): """ Replace the datetime.timedelta in obj.value with an RFC2445 string. """ if not obj.isNative: return obj obj.isNative = False obj.value = timedeltaToString(obj.value) return obj
[ "def", "transformFromNative", "(", "obj", ")", ":", "if", "not", "obj", ".", "isNative", ":", "return", "obj", "obj", ".", "isNative", "=", "False", "obj", ".", "value", "=", "timedeltaToString", "(", "obj", ".", "value", ")", "return", "obj" ]
Replace the datetime.timedelta in obj.value with an RFC2445 string.
[ "Replace", "the", "datetime", ".", "timedelta", "in", "obj", ".", "value", "with", "an", "RFC2445", "string", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1352-L1360
2,045
eventable/vobject
docs/build/lib/vobject/icalendar.py
Trigger.transformToNative
def transformToNative(obj): """ Turn obj.value into a timedelta or datetime. """ if obj.isNative: return obj value = getattr(obj, 'value_param', 'DURATION').upper() if hasattr(obj, 'value_param'): del obj.value_param if obj.value == '': obj.isNative = True return obj elif value == 'DURATION': try: return Duration.transformToNative(obj) except ParseError: logger.warning("TRIGGER not recognized as DURATION, trying " "DATE-TIME, because iCal sometimes exports " "DATE-TIMEs without setting VALUE=DATE-TIME") try: obj.isNative = False dt = DateTimeBehavior.transformToNative(obj) return dt except: msg = "TRIGGER with no VALUE not recognized as DURATION " \ "or as DATE-TIME" raise ParseError(msg) elif value == 'DATE-TIME': # TRIGGERs with DATE-TIME values must be in UTC, we could validate # that fact, for now we take it on faith. return DateTimeBehavior.transformToNative(obj) else: raise ParseError("VALUE must be DURATION or DATE-TIME")
python
def transformToNative(obj): """ Turn obj.value into a timedelta or datetime. """ if obj.isNative: return obj value = getattr(obj, 'value_param', 'DURATION').upper() if hasattr(obj, 'value_param'): del obj.value_param if obj.value == '': obj.isNative = True return obj elif value == 'DURATION': try: return Duration.transformToNative(obj) except ParseError: logger.warning("TRIGGER not recognized as DURATION, trying " "DATE-TIME, because iCal sometimes exports " "DATE-TIMEs without setting VALUE=DATE-TIME") try: obj.isNative = False dt = DateTimeBehavior.transformToNative(obj) return dt except: msg = "TRIGGER with no VALUE not recognized as DURATION " \ "or as DATE-TIME" raise ParseError(msg) elif value == 'DATE-TIME': # TRIGGERs with DATE-TIME values must be in UTC, we could validate # that fact, for now we take it on faith. return DateTimeBehavior.transformToNative(obj) else: raise ParseError("VALUE must be DURATION or DATE-TIME")
[ "def", "transformToNative", "(", "obj", ")", ":", "if", "obj", ".", "isNative", ":", "return", "obj", "value", "=", "getattr", "(", "obj", ",", "'value_param'", ",", "'DURATION'", ")", ".", "upper", "(", ")", "if", "hasattr", "(", "obj", ",", "'value_param'", ")", ":", "del", "obj", ".", "value_param", "if", "obj", ".", "value", "==", "''", ":", "obj", ".", "isNative", "=", "True", "return", "obj", "elif", "value", "==", "'DURATION'", ":", "try", ":", "return", "Duration", ".", "transformToNative", "(", "obj", ")", "except", "ParseError", ":", "logger", ".", "warning", "(", "\"TRIGGER not recognized as DURATION, trying \"", "\"DATE-TIME, because iCal sometimes exports \"", "\"DATE-TIMEs without setting VALUE=DATE-TIME\"", ")", "try", ":", "obj", ".", "isNative", "=", "False", "dt", "=", "DateTimeBehavior", ".", "transformToNative", "(", "obj", ")", "return", "dt", "except", ":", "msg", "=", "\"TRIGGER with no VALUE not recognized as DURATION \"", "\"or as DATE-TIME\"", "raise", "ParseError", "(", "msg", ")", "elif", "value", "==", "'DATE-TIME'", ":", "# TRIGGERs with DATE-TIME values must be in UTC, we could validate", "# that fact, for now we take it on faith.", "return", "DateTimeBehavior", ".", "transformToNative", "(", "obj", ")", "else", ":", "raise", "ParseError", "(", "\"VALUE must be DURATION or DATE-TIME\"", ")" ]
Turn obj.value into a timedelta or datetime.
[ "Turn", "obj", ".", "value", "into", "a", "timedelta", "or", "datetime", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1374-L1406
2,046
eventable/vobject
docs/build/lib/vobject/icalendar.py
PeriodBehavior.transformToNative
def transformToNative(obj): """ Convert comma separated periods into tuples. """ if obj.isNative: return obj obj.isNative = True if obj.value == '': obj.value = [] return obj tzinfo = getTzid(getattr(obj, 'tzid_param', None)) obj.value = [stringToPeriod(x, tzinfo) for x in obj.value.split(",")] return obj
python
def transformToNative(obj): """ Convert comma separated periods into tuples. """ if obj.isNative: return obj obj.isNative = True if obj.value == '': obj.value = [] return obj tzinfo = getTzid(getattr(obj, 'tzid_param', None)) obj.value = [stringToPeriod(x, tzinfo) for x in obj.value.split(",")] return obj
[ "def", "transformToNative", "(", "obj", ")", ":", "if", "obj", ".", "isNative", ":", "return", "obj", "obj", ".", "isNative", "=", "True", "if", "obj", ".", "value", "==", "''", ":", "obj", ".", "value", "=", "[", "]", "return", "obj", "tzinfo", "=", "getTzid", "(", "getattr", "(", "obj", ",", "'tzid_param'", ",", "None", ")", ")", "obj", ".", "value", "=", "[", "stringToPeriod", "(", "x", ",", "tzinfo", ")", "for", "x", "in", "obj", ".", "value", ".", "split", "(", "\",\"", ")", "]", "return", "obj" ]
Convert comma separated periods into tuples.
[ "Convert", "comma", "separated", "periods", "into", "tuples", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1428-L1440
2,047
eventable/vobject
docs/build/lib/vobject/icalendar.py
PeriodBehavior.transformFromNative
def transformFromNative(cls, obj): """ Convert the list of tuples in obj.value to strings. """ if obj.isNative: obj.isNative = False transformed = [] for tup in obj.value: transformed.append(periodToString(tup, cls.forceUTC)) if len(transformed) > 0: tzid = TimezoneComponent.registerTzinfo(tup[0].tzinfo) if not cls.forceUTC and tzid is not None: obj.tzid_param = tzid obj.value = ','.join(transformed) return obj
python
def transformFromNative(cls, obj): """ Convert the list of tuples in obj.value to strings. """ if obj.isNative: obj.isNative = False transformed = [] for tup in obj.value: transformed.append(periodToString(tup, cls.forceUTC)) if len(transformed) > 0: tzid = TimezoneComponent.registerTzinfo(tup[0].tzinfo) if not cls.forceUTC and tzid is not None: obj.tzid_param = tzid obj.value = ','.join(transformed) return obj
[ "def", "transformFromNative", "(", "cls", ",", "obj", ")", ":", "if", "obj", ".", "isNative", ":", "obj", ".", "isNative", "=", "False", "transformed", "=", "[", "]", "for", "tup", "in", "obj", ".", "value", ":", "transformed", ".", "append", "(", "periodToString", "(", "tup", ",", "cls", ".", "forceUTC", ")", ")", "if", "len", "(", "transformed", ")", ">", "0", ":", "tzid", "=", "TimezoneComponent", ".", "registerTzinfo", "(", "tup", "[", "0", "]", ".", "tzinfo", ")", "if", "not", "cls", ".", "forceUTC", "and", "tzid", "is", "not", "None", ":", "obj", ".", "tzid_param", "=", "tzid", "obj", ".", "value", "=", "','", ".", "join", "(", "transformed", ")", "return", "obj" ]
Convert the list of tuples in obj.value to strings.
[ "Convert", "the", "list", "of", "tuples", "in", "obj", ".", "value", "to", "strings", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1443-L1459
2,048
eventable/vobject
vobject/vcard.py
serializeFields
def serializeFields(obj, order=None): """ Turn an object's fields into a ';' and ',' seperated string. If order is None, obj should be a list, backslash escape each field and return a ';' separated string. """ fields = [] if order is None: fields = [backslashEscape(val) for val in obj] else: for field in order: escapedValueList = [backslashEscape(val) for val in toList(getattr(obj, field))] fields.append(','.join(escapedValueList)) return ';'.join(fields)
python
def serializeFields(obj, order=None): """ Turn an object's fields into a ';' and ',' seperated string. If order is None, obj should be a list, backslash escape each field and return a ';' separated string. """ fields = [] if order is None: fields = [backslashEscape(val) for val in obj] else: for field in order: escapedValueList = [backslashEscape(val) for val in toList(getattr(obj, field))] fields.append(','.join(escapedValueList)) return ';'.join(fields)
[ "def", "serializeFields", "(", "obj", ",", "order", "=", "None", ")", ":", "fields", "=", "[", "]", "if", "order", "is", "None", ":", "fields", "=", "[", "backslashEscape", "(", "val", ")", "for", "val", "in", "obj", "]", "else", ":", "for", "field", "in", "order", ":", "escapedValueList", "=", "[", "backslashEscape", "(", "val", ")", "for", "val", "in", "toList", "(", "getattr", "(", "obj", ",", "field", ")", ")", "]", "fields", ".", "append", "(", "','", ".", "join", "(", "escapedValueList", ")", ")", "return", "';'", ".", "join", "(", "fields", ")" ]
Turn an object's fields into a ';' and ',' seperated string. If order is None, obj should be a list, backslash escape each field and return a ';' separated string.
[ "Turn", "an", "object", "s", "fields", "into", "a", ";", "and", "seperated", "string", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/vcard.py#L264-L279
2,049
eventable/vobject
vobject/vcard.py
Address.toString
def toString(val, join_char='\n'): """ Turn a string or array value into a string. """ if type(val) in (list, tuple): return join_char.join(val) return val
python
def toString(val, join_char='\n'): """ Turn a string or array value into a string. """ if type(val) in (list, tuple): return join_char.join(val) return val
[ "def", "toString", "(", "val", ",", "join_char", "=", "'\\n'", ")", ":", "if", "type", "(", "val", ")", "in", "(", "list", ",", "tuple", ")", ":", "return", "join_char", ".", "join", "(", "val", ")", "return", "val" ]
Turn a string or array value into a string.
[ "Turn", "a", "string", "or", "array", "value", "into", "a", "string", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/vcard.py#L75-L81
2,050
eventable/vobject
vobject/vcard.py
NameBehavior.transformToNative
def transformToNative(obj): """ Turn obj.value into a Name. """ if obj.isNative: return obj obj.isNative = True obj.value = Name(**dict(zip(NAME_ORDER, splitFields(obj.value)))) return obj
python
def transformToNative(obj): """ Turn obj.value into a Name. """ if obj.isNative: return obj obj.isNative = True obj.value = Name(**dict(zip(NAME_ORDER, splitFields(obj.value)))) return obj
[ "def", "transformToNative", "(", "obj", ")", ":", "if", "obj", ".", "isNative", ":", "return", "obj", "obj", ".", "isNative", "=", "True", "obj", ".", "value", "=", "Name", "(", "*", "*", "dict", "(", "zip", "(", "NAME_ORDER", ",", "splitFields", "(", "obj", ".", "value", ")", ")", ")", ")", "return", "obj" ]
Turn obj.value into a Name.
[ "Turn", "obj", ".", "value", "into", "a", "Name", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/vcard.py#L294-L302
2,051
eventable/vobject
vobject/vcard.py
NameBehavior.transformFromNative
def transformFromNative(obj): """ Replace the Name in obj.value with a string. """ obj.isNative = False obj.value = serializeFields(obj.value, NAME_ORDER) return obj
python
def transformFromNative(obj): """ Replace the Name in obj.value with a string. """ obj.isNative = False obj.value = serializeFields(obj.value, NAME_ORDER) return obj
[ "def", "transformFromNative", "(", "obj", ")", ":", "obj", ".", "isNative", "=", "False", "obj", ".", "value", "=", "serializeFields", "(", "obj", ".", "value", ",", "NAME_ORDER", ")", "return", "obj" ]
Replace the Name in obj.value with a string.
[ "Replace", "the", "Name", "in", "obj", ".", "value", "with", "a", "string", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/vcard.py#L305-L311
2,052
eventable/vobject
vobject/vcard.py
AddressBehavior.transformToNative
def transformToNative(obj): """ Turn obj.value into an Address. """ if obj.isNative: return obj obj.isNative = True obj.value = Address(**dict(zip(ADDRESS_ORDER, splitFields(obj.value)))) return obj
python
def transformToNative(obj): """ Turn obj.value into an Address. """ if obj.isNative: return obj obj.isNative = True obj.value = Address(**dict(zip(ADDRESS_ORDER, splitFields(obj.value)))) return obj
[ "def", "transformToNative", "(", "obj", ")", ":", "if", "obj", ".", "isNative", ":", "return", "obj", "obj", ".", "isNative", "=", "True", "obj", ".", "value", "=", "Address", "(", "*", "*", "dict", "(", "zip", "(", "ADDRESS_ORDER", ",", "splitFields", "(", "obj", ".", "value", ")", ")", ")", ")", "return", "obj" ]
Turn obj.value into an Address.
[ "Turn", "obj", ".", "value", "into", "an", "Address", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/vcard.py#L322-L330
2,053
eventable/vobject
vobject/vcard.py
OrgBehavior.transformToNative
def transformToNative(obj): """ Turn obj.value into a list. """ if obj.isNative: return obj obj.isNative = True obj.value = splitFields(obj.value) return obj
python
def transformToNative(obj): """ Turn obj.value into a list. """ if obj.isNative: return obj obj.isNative = True obj.value = splitFields(obj.value) return obj
[ "def", "transformToNative", "(", "obj", ")", ":", "if", "obj", ".", "isNative", ":", "return", "obj", "obj", ".", "isNative", "=", "True", "obj", ".", "value", "=", "splitFields", "(", "obj", ".", "value", ")", "return", "obj" ]
Turn obj.value into a list.
[ "Turn", "obj", ".", "value", "into", "a", "list", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/vcard.py#L350-L358
2,054
eventable/vobject
docs/build/lib/vobject/vcard.py
VCardTextBehavior.decode
def decode(cls, line): """ Remove backslash escaping from line.valueDecode line, either to remove backslash espacing, or to decode base64 encoding. The content line should contain a ENCODING=b for base64 encoding, but Apple Addressbook seems to export a singleton parameter of 'BASE64', which does not match the 3.0 vCard spec. If we encouter that, then we transform the parameter to ENCODING=b """ if line.encoded: if 'BASE64' in line.singletonparams: line.singletonparams.remove('BASE64') line.encoding_param = cls.base64string encoding = getattr(line, 'encoding_param', None) if encoding: line.value = codecs.decode(line.value.encode("utf-8"), "base64") else: line.value = stringToTextValues(line.value)[0] line.encoded=False
python
def decode(cls, line): """ Remove backslash escaping from line.valueDecode line, either to remove backslash espacing, or to decode base64 encoding. The content line should contain a ENCODING=b for base64 encoding, but Apple Addressbook seems to export a singleton parameter of 'BASE64', which does not match the 3.0 vCard spec. If we encouter that, then we transform the parameter to ENCODING=b """ if line.encoded: if 'BASE64' in line.singletonparams: line.singletonparams.remove('BASE64') line.encoding_param = cls.base64string encoding = getattr(line, 'encoding_param', None) if encoding: line.value = codecs.decode(line.value.encode("utf-8"), "base64") else: line.value = stringToTextValues(line.value)[0] line.encoded=False
[ "def", "decode", "(", "cls", ",", "line", ")", ":", "if", "line", ".", "encoded", ":", "if", "'BASE64'", "in", "line", ".", "singletonparams", ":", "line", ".", "singletonparams", ".", "remove", "(", "'BASE64'", ")", "line", ".", "encoding_param", "=", "cls", ".", "base64string", "encoding", "=", "getattr", "(", "line", ",", "'encoding_param'", ",", "None", ")", "if", "encoding", ":", "line", ".", "value", "=", "codecs", ".", "decode", "(", "line", ".", "value", ".", "encode", "(", "\"utf-8\"", ")", ",", "\"base64\"", ")", "else", ":", "line", ".", "value", "=", "stringToTextValues", "(", "line", ".", "value", ")", "[", "0", "]", "line", ".", "encoded", "=", "False" ]
Remove backslash escaping from line.valueDecode line, either to remove backslash espacing, or to decode base64 encoding. The content line should contain a ENCODING=b for base64 encoding, but Apple Addressbook seems to export a singleton parameter of 'BASE64', which does not match the 3.0 vCard spec. If we encouter that, then we transform the parameter to ENCODING=b
[ "Remove", "backslash", "escaping", "from", "line", ".", "valueDecode", "line", "either", "to", "remove", "backslash", "espacing", "or", "to", "decode", "base64", "encoding", ".", "The", "content", "line", "should", "contain", "a", "ENCODING", "=", "b", "for", "base64", "encoding", "but", "Apple", "Addressbook", "seems", "to", "export", "a", "singleton", "parameter", "of", "BASE64", "which", "does", "not", "match", "the", "3", ".", "0", "vCard", "spec", ".", "If", "we", "encouter", "that", "then", "we", "transform", "the", "parameter", "to", "ENCODING", "=", "b" ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/vcard.py#L124-L142
2,055
eventable/vobject
vobject/behavior.py
Behavior.validate
def validate(cls, obj, raiseException=False, complainUnrecognized=False): """Check if the object satisfies this behavior's requirements. @param obj: The L{ContentLine<base.ContentLine>} or L{Component<base.Component>} to be validated. @param raiseException: If True, raise a L{base.ValidateError} on validation failure. Otherwise return a boolean. @param complainUnrecognized: If True, fail to validate if an uncrecognized parameter or child is found. Otherwise log the lack of recognition. """ if not cls.allowGroup and obj.group is not None: err = "{0} has a group, but this object doesn't support groups".format(obj) raise base.VObjectError(err) if isinstance(obj, base.ContentLine): return cls.lineValidate(obj, raiseException, complainUnrecognized) elif isinstance(obj, base.Component): count = {} for child in obj.getChildren(): if not child.validate(raiseException, complainUnrecognized): return False name = child.name.upper() count[name] = count.get(name, 0) + 1 for key, val in cls.knownChildren.items(): if count.get(key, 0) < val[0]: if raiseException: m = "{0} components must contain at least {1} {2}" raise base.ValidateError(m .format(cls.name, val[0], key)) return False if val[1] and count.get(key, 0) > val[1]: if raiseException: m = "{0} components cannot contain more than {1} {2}" raise base.ValidateError(m.format(cls.name, val[1], key)) return False return True else: err = "{0} is not a Component or Contentline".format(obj) raise base.VObjectError(err)
python
def validate(cls, obj, raiseException=False, complainUnrecognized=False): """Check if the object satisfies this behavior's requirements. @param obj: The L{ContentLine<base.ContentLine>} or L{Component<base.Component>} to be validated. @param raiseException: If True, raise a L{base.ValidateError} on validation failure. Otherwise return a boolean. @param complainUnrecognized: If True, fail to validate if an uncrecognized parameter or child is found. Otherwise log the lack of recognition. """ if not cls.allowGroup and obj.group is not None: err = "{0} has a group, but this object doesn't support groups".format(obj) raise base.VObjectError(err) if isinstance(obj, base.ContentLine): return cls.lineValidate(obj, raiseException, complainUnrecognized) elif isinstance(obj, base.Component): count = {} for child in obj.getChildren(): if not child.validate(raiseException, complainUnrecognized): return False name = child.name.upper() count[name] = count.get(name, 0) + 1 for key, val in cls.knownChildren.items(): if count.get(key, 0) < val[0]: if raiseException: m = "{0} components must contain at least {1} {2}" raise base.ValidateError(m .format(cls.name, val[0], key)) return False if val[1] and count.get(key, 0) > val[1]: if raiseException: m = "{0} components cannot contain more than {1} {2}" raise base.ValidateError(m.format(cls.name, val[1], key)) return False return True else: err = "{0} is not a Component or Contentline".format(obj) raise base.VObjectError(err)
[ "def", "validate", "(", "cls", ",", "obj", ",", "raiseException", "=", "False", ",", "complainUnrecognized", "=", "False", ")", ":", "if", "not", "cls", ".", "allowGroup", "and", "obj", ".", "group", "is", "not", "None", ":", "err", "=", "\"{0} has a group, but this object doesn't support groups\"", ".", "format", "(", "obj", ")", "raise", "base", ".", "VObjectError", "(", "err", ")", "if", "isinstance", "(", "obj", ",", "base", ".", "ContentLine", ")", ":", "return", "cls", ".", "lineValidate", "(", "obj", ",", "raiseException", ",", "complainUnrecognized", ")", "elif", "isinstance", "(", "obj", ",", "base", ".", "Component", ")", ":", "count", "=", "{", "}", "for", "child", "in", "obj", ".", "getChildren", "(", ")", ":", "if", "not", "child", ".", "validate", "(", "raiseException", ",", "complainUnrecognized", ")", ":", "return", "False", "name", "=", "child", ".", "name", ".", "upper", "(", ")", "count", "[", "name", "]", "=", "count", ".", "get", "(", "name", ",", "0", ")", "+", "1", "for", "key", ",", "val", "in", "cls", ".", "knownChildren", ".", "items", "(", ")", ":", "if", "count", ".", "get", "(", "key", ",", "0", ")", "<", "val", "[", "0", "]", ":", "if", "raiseException", ":", "m", "=", "\"{0} components must contain at least {1} {2}\"", "raise", "base", ".", "ValidateError", "(", "m", ".", "format", "(", "cls", ".", "name", ",", "val", "[", "0", "]", ",", "key", ")", ")", "return", "False", "if", "val", "[", "1", "]", "and", "count", ".", "get", "(", "key", ",", "0", ")", ">", "val", "[", "1", "]", ":", "if", "raiseException", ":", "m", "=", "\"{0} components cannot contain more than {1} {2}\"", "raise", "base", ".", "ValidateError", "(", "m", ".", "format", "(", "cls", ".", "name", ",", "val", "[", "1", "]", ",", "key", ")", ")", "return", "False", "return", "True", "else", ":", "err", "=", "\"{0} is not a Component or Contentline\"", ".", "format", "(", "obj", ")", "raise", "base", ".", "VObjectError", "(", "err", ")" ]
Check if the object satisfies this behavior's requirements. @param obj: The L{ContentLine<base.ContentLine>} or L{Component<base.Component>} to be validated. @param raiseException: If True, raise a L{base.ValidateError} on validation failure. Otherwise return a boolean. @param complainUnrecognized: If True, fail to validate if an uncrecognized parameter or child is found. Otherwise log the lack of recognition.
[ "Check", "if", "the", "object", "satisfies", "this", "behavior", "s", "requirements", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/behavior.py#L63-L103
2,056
eventable/vobject
vobject/win32tz.py
pickNthWeekday
def pickNthWeekday(year, month, dayofweek, hour, minute, whichweek): """dayofweek == 0 means Sunday, whichweek > 4 means last instance""" first = datetime.datetime(year=year, month=month, hour=hour, minute=minute, day=1) weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7 + 1)) for n in xrange(whichweek - 1, -1, -1): dt = weekdayone + n * WEEKS if dt.month == month: return dt
python
def pickNthWeekday(year, month, dayofweek, hour, minute, whichweek): """dayofweek == 0 means Sunday, whichweek > 4 means last instance""" first = datetime.datetime(year=year, month=month, hour=hour, minute=minute, day=1) weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7 + 1)) for n in xrange(whichweek - 1, -1, -1): dt = weekdayone + n * WEEKS if dt.month == month: return dt
[ "def", "pickNthWeekday", "(", "year", ",", "month", ",", "dayofweek", ",", "hour", ",", "minute", ",", "whichweek", ")", ":", "first", "=", "datetime", ".", "datetime", "(", "year", "=", "year", ",", "month", "=", "month", ",", "hour", "=", "hour", ",", "minute", "=", "minute", ",", "day", "=", "1", ")", "weekdayone", "=", "first", ".", "replace", "(", "day", "=", "(", "(", "dayofweek", "-", "first", ".", "isoweekday", "(", ")", ")", "%", "7", "+", "1", ")", ")", "for", "n", "in", "xrange", "(", "whichweek", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "dt", "=", "weekdayone", "+", "n", "*", "WEEKS", "if", "dt", ".", "month", "==", "month", ":", "return", "dt" ]
dayofweek == 0 means Sunday, whichweek > 4 means last instance
[ "dayofweek", "==", "0", "means", "Sunday", "whichweek", ">", "4", "means", "last", "instance" ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/win32tz.py#L77-L85
2,057
eventable/vobject
vobject/ics_diff.py
deleteExtraneous
def deleteExtraneous(component, ignore_dtstamp=False): """ Recursively walk the component's children, deleting extraneous details like X-VOBJ-ORIGINAL-TZID. """ for comp in component.components(): deleteExtraneous(comp, ignore_dtstamp) for line in component.lines(): if 'X-VOBJ-ORIGINAL-TZID' in line.params: del line.params['X-VOBJ-ORIGINAL-TZID'] if ignore_dtstamp and hasattr(component, 'dtstamp_list'): del component.dtstamp_list
python
def deleteExtraneous(component, ignore_dtstamp=False): """ Recursively walk the component's children, deleting extraneous details like X-VOBJ-ORIGINAL-TZID. """ for comp in component.components(): deleteExtraneous(comp, ignore_dtstamp) for line in component.lines(): if 'X-VOBJ-ORIGINAL-TZID' in line.params: del line.params['X-VOBJ-ORIGINAL-TZID'] if ignore_dtstamp and hasattr(component, 'dtstamp_list'): del component.dtstamp_list
[ "def", "deleteExtraneous", "(", "component", ",", "ignore_dtstamp", "=", "False", ")", ":", "for", "comp", "in", "component", ".", "components", "(", ")", ":", "deleteExtraneous", "(", "comp", ",", "ignore_dtstamp", ")", "for", "line", "in", "component", ".", "lines", "(", ")", ":", "if", "'X-VOBJ-ORIGINAL-TZID'", "in", "line", ".", "params", ":", "del", "line", ".", "params", "[", "'X-VOBJ-ORIGINAL-TZID'", "]", "if", "ignore_dtstamp", "and", "hasattr", "(", "component", ",", "'dtstamp_list'", ")", ":", "del", "component", ".", "dtstamp_list" ]
Recursively walk the component's children, deleting extraneous details like X-VOBJ-ORIGINAL-TZID.
[ "Recursively", "walk", "the", "component", "s", "children", "deleting", "extraneous", "details", "like", "X", "-", "VOBJ", "-", "ORIGINAL", "-", "TZID", "." ]
498555a553155ea9b26aace93332ae79365ecb31
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/ics_diff.py#L37-L48
2,058
SoftwareDefinedBuildings/XBOS
apps/hole_filling/pelican/backfill.py
fillPelicanHole
def fillPelicanHole(site, username, password, tstat_name, start_time, end_time): """Fill a hole in a Pelican thermostat's data stream. Arguments: site -- The thermostat's Pelican site name username -- The Pelican username for the site password -- The Pelican password for the site tstat_name -- The name of the thermostat, as identified by Pelican start_time -- The start of the data hole in UTC, e.g. "2018-01-29 15:00:00" end_time -- The end of the data hole in UTC, e.g. "2018-01-29 16:00:00" Returns: A Pandas dataframe with historical Pelican data that falls between the specified start and end times. Note that this function assumes the Pelican thermostat's local time zone is US/Pacific. It will properly handle PST vs. PDT. """ start = datetime.strptime(start_time, _INPUT_TIME_FORMAT).replace(tzinfo=pytz.utc).astimezone(_pelican_time) end = datetime.strptime(end_time, _INPUT_TIME_FORMAT).replace(tzinfo=pytz.utc).astimezone(_pelican_time) heat_needs_fan = _lookupHeatNeedsFan(site, username, password, tstat_name) if heat_needs_fan is None: return None # Pelican's API only allows a query covering a time range of up to 1 month # So we may need run multiple requests for historical data history_blocks = [] while start < end: block_start = start block_end = min(start + timedelta(days=30), end) blocks = _lookupHistoricalData(site, username, password, tstat_name, block_start, block_end) if blocks is None: return None history_blocks.extend(blocks) start += timedelta(days=30, minutes=1) output_rows = [] for block in history_blocks: runStatus = block.find("runStatus").text if runStatus.startswith("Heat"): fanState = (heatNeedsFan == "Yes") else: fanState = (runStatus != "Off") api_time = datetime.strptime(block.find("timestamp").text, "%Y-%m-%dT%H:%M").replace(tzinfo=_pelican_time) # Need to convert seconds to nanoseconds timestamp = int(api_time.timestamp() * 10**9) output_rows.append({ "temperature": float(block.find("temperature").text), "relative_humidity": float(block.find("humidity").text), "heating_setpoint": float(block.find("heatSetting").text), "cooling_setpoint": float(block.find("coolSetting").text), # Driver explicitly uses "Schedule" field, but we don't have this in history "override": block.find("setBy").text != "Schedule", "fan": fanState, "mode": _mode_name_mappings[block.find("system").text], "state": _state_mappings.get(runStatus, 0), "time": timestamp, }) df = pd.DataFrame(output_rows) df.drop_duplicates(subset="time", keep="first", inplace=True) return df
python
def fillPelicanHole(site, username, password, tstat_name, start_time, end_time): """Fill a hole in a Pelican thermostat's data stream. Arguments: site -- The thermostat's Pelican site name username -- The Pelican username for the site password -- The Pelican password for the site tstat_name -- The name of the thermostat, as identified by Pelican start_time -- The start of the data hole in UTC, e.g. "2018-01-29 15:00:00" end_time -- The end of the data hole in UTC, e.g. "2018-01-29 16:00:00" Returns: A Pandas dataframe with historical Pelican data that falls between the specified start and end times. Note that this function assumes the Pelican thermostat's local time zone is US/Pacific. It will properly handle PST vs. PDT. """ start = datetime.strptime(start_time, _INPUT_TIME_FORMAT).replace(tzinfo=pytz.utc).astimezone(_pelican_time) end = datetime.strptime(end_time, _INPUT_TIME_FORMAT).replace(tzinfo=pytz.utc).astimezone(_pelican_time) heat_needs_fan = _lookupHeatNeedsFan(site, username, password, tstat_name) if heat_needs_fan is None: return None # Pelican's API only allows a query covering a time range of up to 1 month # So we may need run multiple requests for historical data history_blocks = [] while start < end: block_start = start block_end = min(start + timedelta(days=30), end) blocks = _lookupHistoricalData(site, username, password, tstat_name, block_start, block_end) if blocks is None: return None history_blocks.extend(blocks) start += timedelta(days=30, minutes=1) output_rows = [] for block in history_blocks: runStatus = block.find("runStatus").text if runStatus.startswith("Heat"): fanState = (heatNeedsFan == "Yes") else: fanState = (runStatus != "Off") api_time = datetime.strptime(block.find("timestamp").text, "%Y-%m-%dT%H:%M").replace(tzinfo=_pelican_time) # Need to convert seconds to nanoseconds timestamp = int(api_time.timestamp() * 10**9) output_rows.append({ "temperature": float(block.find("temperature").text), "relative_humidity": float(block.find("humidity").text), "heating_setpoint": float(block.find("heatSetting").text), "cooling_setpoint": float(block.find("coolSetting").text), # Driver explicitly uses "Schedule" field, but we don't have this in history "override": block.find("setBy").text != "Schedule", "fan": fanState, "mode": _mode_name_mappings[block.find("system").text], "state": _state_mappings.get(runStatus, 0), "time": timestamp, }) df = pd.DataFrame(output_rows) df.drop_duplicates(subset="time", keep="first", inplace=True) return df
[ "def", "fillPelicanHole", "(", "site", ",", "username", ",", "password", ",", "tstat_name", ",", "start_time", ",", "end_time", ")", ":", "start", "=", "datetime", ".", "strptime", "(", "start_time", ",", "_INPUT_TIME_FORMAT", ")", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "utc", ")", ".", "astimezone", "(", "_pelican_time", ")", "end", "=", "datetime", ".", "strptime", "(", "end_time", ",", "_INPUT_TIME_FORMAT", ")", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "utc", ")", ".", "astimezone", "(", "_pelican_time", ")", "heat_needs_fan", "=", "_lookupHeatNeedsFan", "(", "site", ",", "username", ",", "password", ",", "tstat_name", ")", "if", "heat_needs_fan", "is", "None", ":", "return", "None", "# Pelican's API only allows a query covering a time range of up to 1 month", "# So we may need run multiple requests for historical data", "history_blocks", "=", "[", "]", "while", "start", "<", "end", ":", "block_start", "=", "start", "block_end", "=", "min", "(", "start", "+", "timedelta", "(", "days", "=", "30", ")", ",", "end", ")", "blocks", "=", "_lookupHistoricalData", "(", "site", ",", "username", ",", "password", ",", "tstat_name", ",", "block_start", ",", "block_end", ")", "if", "blocks", "is", "None", ":", "return", "None", "history_blocks", ".", "extend", "(", "blocks", ")", "start", "+=", "timedelta", "(", "days", "=", "30", ",", "minutes", "=", "1", ")", "output_rows", "=", "[", "]", "for", "block", "in", "history_blocks", ":", "runStatus", "=", "block", ".", "find", "(", "\"runStatus\"", ")", ".", "text", "if", "runStatus", ".", "startswith", "(", "\"Heat\"", ")", ":", "fanState", "=", "(", "heatNeedsFan", "==", "\"Yes\"", ")", "else", ":", "fanState", "=", "(", "runStatus", "!=", "\"Off\"", ")", "api_time", "=", "datetime", ".", "strptime", "(", "block", ".", "find", "(", "\"timestamp\"", ")", ".", "text", ",", "\"%Y-%m-%dT%H:%M\"", ")", ".", "replace", "(", "tzinfo", "=", "_pelican_time", ")", "# Need to convert seconds to nanoseconds", "timestamp", "=", "int", "(", "api_time", ".", "timestamp", "(", ")", "*", "10", "**", "9", ")", "output_rows", ".", "append", "(", "{", "\"temperature\"", ":", "float", "(", "block", ".", "find", "(", "\"temperature\"", ")", ".", "text", ")", ",", "\"relative_humidity\"", ":", "float", "(", "block", ".", "find", "(", "\"humidity\"", ")", ".", "text", ")", ",", "\"heating_setpoint\"", ":", "float", "(", "block", ".", "find", "(", "\"heatSetting\"", ")", ".", "text", ")", ",", "\"cooling_setpoint\"", ":", "float", "(", "block", ".", "find", "(", "\"coolSetting\"", ")", ".", "text", ")", ",", "# Driver explicitly uses \"Schedule\" field, but we don't have this in history", "\"override\"", ":", "block", ".", "find", "(", "\"setBy\"", ")", ".", "text", "!=", "\"Schedule\"", ",", "\"fan\"", ":", "fanState", ",", "\"mode\"", ":", "_mode_name_mappings", "[", "block", ".", "find", "(", "\"system\"", ")", ".", "text", "]", ",", "\"state\"", ":", "_state_mappings", ".", "get", "(", "runStatus", ",", "0", ")", ",", "\"time\"", ":", "timestamp", ",", "}", ")", "df", "=", "pd", ".", "DataFrame", "(", "output_rows", ")", "df", ".", "drop_duplicates", "(", "subset", "=", "\"time\"", ",", "keep", "=", "\"first\"", ",", "inplace", "=", "True", ")", "return", "df" ]
Fill a hole in a Pelican thermostat's data stream. Arguments: site -- The thermostat's Pelican site name username -- The Pelican username for the site password -- The Pelican password for the site tstat_name -- The name of the thermostat, as identified by Pelican start_time -- The start of the data hole in UTC, e.g. "2018-01-29 15:00:00" end_time -- The end of the data hole in UTC, e.g. "2018-01-29 16:00:00" Returns: A Pandas dataframe with historical Pelican data that falls between the specified start and end times. Note that this function assumes the Pelican thermostat's local time zone is US/Pacific. It will properly handle PST vs. PDT.
[ "Fill", "a", "hole", "in", "a", "Pelican", "thermostat", "s", "data", "stream", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/hole_filling/pelican/backfill.py#L73-L137
2,059
SoftwareDefinedBuildings/XBOS
apps/data_analysis/XBOS_data_analytics/Preprocess_Data.py
Preprocess_Data.add_degree_days
def add_degree_days(self, col='OAT', hdh_cpoint=65, cdh_cpoint=65): """ Adds Heating & Cooling Degree Hours. Parameters ---------- col : str Column name which contains the outdoor air temperature. hdh_cpoint : int Heating degree hours. Defaults to 65. cdh_cpoint : int Cooling degree hours. Defaults to 65. """ if self.preprocessed_data.empty: data = self.original_data else: data = self.preprocessed_data # Calculate hdh data['hdh'] = data[col] over_hdh = data.loc[:, col] > hdh_cpoint data.loc[over_hdh, 'hdh'] = 0 data.loc[~over_hdh, 'hdh'] = hdh_cpoint - data.loc[~over_hdh, col] # Calculate cdh data['cdh'] = data[col] under_cdh = data.loc[:, col] < cdh_cpoint data.loc[under_cdh, 'cdh'] = 0 data.loc[~under_cdh, 'cdh'] = data.loc[~under_cdh, col] - cdh_cpoint self.preprocessed_data = data
python
def add_degree_days(self, col='OAT', hdh_cpoint=65, cdh_cpoint=65): """ Adds Heating & Cooling Degree Hours. Parameters ---------- col : str Column name which contains the outdoor air temperature. hdh_cpoint : int Heating degree hours. Defaults to 65. cdh_cpoint : int Cooling degree hours. Defaults to 65. """ if self.preprocessed_data.empty: data = self.original_data else: data = self.preprocessed_data # Calculate hdh data['hdh'] = data[col] over_hdh = data.loc[:, col] > hdh_cpoint data.loc[over_hdh, 'hdh'] = 0 data.loc[~over_hdh, 'hdh'] = hdh_cpoint - data.loc[~over_hdh, col] # Calculate cdh data['cdh'] = data[col] under_cdh = data.loc[:, col] < cdh_cpoint data.loc[under_cdh, 'cdh'] = 0 data.loc[~under_cdh, 'cdh'] = data.loc[~under_cdh, col] - cdh_cpoint self.preprocessed_data = data
[ "def", "add_degree_days", "(", "self", ",", "col", "=", "'OAT'", ",", "hdh_cpoint", "=", "65", ",", "cdh_cpoint", "=", "65", ")", ":", "if", "self", ".", "preprocessed_data", ".", "empty", ":", "data", "=", "self", ".", "original_data", "else", ":", "data", "=", "self", ".", "preprocessed_data", "# Calculate hdh", "data", "[", "'hdh'", "]", "=", "data", "[", "col", "]", "over_hdh", "=", "data", ".", "loc", "[", ":", ",", "col", "]", ">", "hdh_cpoint", "data", ".", "loc", "[", "over_hdh", ",", "'hdh'", "]", "=", "0", "data", ".", "loc", "[", "~", "over_hdh", ",", "'hdh'", "]", "=", "hdh_cpoint", "-", "data", ".", "loc", "[", "~", "over_hdh", ",", "col", "]", "# Calculate cdh", "data", "[", "'cdh'", "]", "=", "data", "[", "col", "]", "under_cdh", "=", "data", ".", "loc", "[", ":", ",", "col", "]", "<", "cdh_cpoint", "data", ".", "loc", "[", "under_cdh", ",", "'cdh'", "]", "=", "0", "data", ".", "loc", "[", "~", "under_cdh", ",", "'cdh'", "]", "=", "data", ".", "loc", "[", "~", "under_cdh", ",", "col", "]", "-", "cdh_cpoint", "self", ".", "preprocessed_data", "=", "data" ]
Adds Heating & Cooling Degree Hours. Parameters ---------- col : str Column name which contains the outdoor air temperature. hdh_cpoint : int Heating degree hours. Defaults to 65. cdh_cpoint : int Cooling degree hours. Defaults to 65.
[ "Adds", "Heating", "&", "Cooling", "Degree", "Hours", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/data_analysis/XBOS_data_analytics/Preprocess_Data.py#L34-L65
2,060
SoftwareDefinedBuildings/XBOS
apps/data_analysis/XBOS_data_analytics/Preprocess_Data.py
Preprocess_Data.add_col_features
def add_col_features(self, col=None, degree=None): """ Exponentiate columns of dataframe. Basically this function squares/cubes a column. e.g. df[col^2] = pow(df[col], degree) where degree=2. Parameters ---------- col : list(str) Column to exponentiate. degree : list(str) Exponentiation degree. """ if not col and not degree: return else: if isinstance(col, list) and isinstance(degree, list): if len(col) != len(degree): print('col len: ', len(col)) print('degree len: ', len(degree)) raise ValueError('col and degree should have equal length.') else: if self.preprocessed_data.empty: data = self.original_data else: data = self.preprocessed_data for i in range(len(col)): data.loc[:,col[i]+str(degree[i])] = pow(data.loc[:,col[i]],degree[i]) / pow(10,degree[i]-1) self.preprocessed_data = data else: raise TypeError('col and degree should be lists.')
python
def add_col_features(self, col=None, degree=None): """ Exponentiate columns of dataframe. Basically this function squares/cubes a column. e.g. df[col^2] = pow(df[col], degree) where degree=2. Parameters ---------- col : list(str) Column to exponentiate. degree : list(str) Exponentiation degree. """ if not col and not degree: return else: if isinstance(col, list) and isinstance(degree, list): if len(col) != len(degree): print('col len: ', len(col)) print('degree len: ', len(degree)) raise ValueError('col and degree should have equal length.') else: if self.preprocessed_data.empty: data = self.original_data else: data = self.preprocessed_data for i in range(len(col)): data.loc[:,col[i]+str(degree[i])] = pow(data.loc[:,col[i]],degree[i]) / pow(10,degree[i]-1) self.preprocessed_data = data else: raise TypeError('col and degree should be lists.')
[ "def", "add_col_features", "(", "self", ",", "col", "=", "None", ",", "degree", "=", "None", ")", ":", "if", "not", "col", "and", "not", "degree", ":", "return", "else", ":", "if", "isinstance", "(", "col", ",", "list", ")", "and", "isinstance", "(", "degree", ",", "list", ")", ":", "if", "len", "(", "col", ")", "!=", "len", "(", "degree", ")", ":", "print", "(", "'col len: '", ",", "len", "(", "col", ")", ")", "print", "(", "'degree len: '", ",", "len", "(", "degree", ")", ")", "raise", "ValueError", "(", "'col and degree should have equal length.'", ")", "else", ":", "if", "self", ".", "preprocessed_data", ".", "empty", ":", "data", "=", "self", ".", "original_data", "else", ":", "data", "=", "self", ".", "preprocessed_data", "for", "i", "in", "range", "(", "len", "(", "col", ")", ")", ":", "data", ".", "loc", "[", ":", ",", "col", "[", "i", "]", "+", "str", "(", "degree", "[", "i", "]", ")", "]", "=", "pow", "(", "data", ".", "loc", "[", ":", ",", "col", "[", "i", "]", "]", ",", "degree", "[", "i", "]", ")", "/", "pow", "(", "10", ",", "degree", "[", "i", "]", "-", "1", ")", "self", ".", "preprocessed_data", "=", "data", "else", ":", "raise", "TypeError", "(", "'col and degree should be lists.'", ")" ]
Exponentiate columns of dataframe. Basically this function squares/cubes a column. e.g. df[col^2] = pow(df[col], degree) where degree=2. Parameters ---------- col : list(str) Column to exponentiate. degree : list(str) Exponentiation degree.
[ "Exponentiate", "columns", "of", "dataframe", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/data_analysis/XBOS_data_analytics/Preprocess_Data.py#L68-L103
2,061
SoftwareDefinedBuildings/XBOS
apps/data_analysis/XBOS_data_analytics/Preprocess_Data.py
Preprocess_Data.standardize
def standardize(self): """ Standardize data. """ if self.preprocessed_data.empty: data = self.original_data else: data = self.preprocessed_data scaler = preprocessing.StandardScaler() data = pd.DataFrame(scaler.fit_transform(data), columns=data.columns, index=data.index) self.preprocessed_data = data
python
def standardize(self): """ Standardize data. """ if self.preprocessed_data.empty: data = self.original_data else: data = self.preprocessed_data scaler = preprocessing.StandardScaler() data = pd.DataFrame(scaler.fit_transform(data), columns=data.columns, index=data.index) self.preprocessed_data = data
[ "def", "standardize", "(", "self", ")", ":", "if", "self", ".", "preprocessed_data", ".", "empty", ":", "data", "=", "self", ".", "original_data", "else", ":", "data", "=", "self", ".", "preprocessed_data", "scaler", "=", "preprocessing", ".", "StandardScaler", "(", ")", "data", "=", "pd", ".", "DataFrame", "(", "scaler", ".", "fit_transform", "(", "data", ")", ",", "columns", "=", "data", ".", "columns", ",", "index", "=", "data", ".", "index", ")", "self", ".", "preprocessed_data", "=", "data" ]
Standardize data.
[ "Standardize", "data", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/data_analysis/XBOS_data_analytics/Preprocess_Data.py#L106-L116
2,062
SoftwareDefinedBuildings/XBOS
apps/data_analysis/XBOS_data_analytics/Preprocess_Data.py
Preprocess_Data.normalize
def normalize(self): """ Normalize data. """ if self.preprocessed_data.empty: data = self.original_data else: data = self.preprocessed_data data = pd.DataFrame(preprocessing.normalize(data), columns=data.columns, index=data.index) self.preprocessed_data = data
python
def normalize(self): """ Normalize data. """ if self.preprocessed_data.empty: data = self.original_data else: data = self.preprocessed_data data = pd.DataFrame(preprocessing.normalize(data), columns=data.columns, index=data.index) self.preprocessed_data = data
[ "def", "normalize", "(", "self", ")", ":", "if", "self", ".", "preprocessed_data", ".", "empty", ":", "data", "=", "self", ".", "original_data", "else", ":", "data", "=", "self", ".", "preprocessed_data", "data", "=", "pd", ".", "DataFrame", "(", "preprocessing", ".", "normalize", "(", "data", ")", ",", "columns", "=", "data", ".", "columns", ",", "index", "=", "data", ".", "index", ")", "self", ".", "preprocessed_data", "=", "data" ]
Normalize data.
[ "Normalize", "data", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/data_analysis/XBOS_data_analytics/Preprocess_Data.py#L119-L128
2,063
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Preprocess_Data.py
Preprocess_Data.add_time_features
def add_time_features(self, year=False, month=False, week=True, tod=True, dow=True): """ Add time features to dataframe. Parameters ---------- year : bool Year. month : bool Month. week : bool Week. tod : bool Time of Day. dow : bool Day of Week. """ var_to_expand = [] if self.preprocessed_data.empty: data = self.original_data else: data = self.preprocessed_data if year: data["year"] = data.index.year var_to_expand.append("year") if month: data["month"] = data.index.month var_to_expand.append("month") if week: data["week"] = data.index.week var_to_expand.append("week") if tod: data["tod"] = data.index.hour var_to_expand.append("tod") if dow: data["dow"] = data.index.weekday var_to_expand.append("dow") # One-hot encode the time features for var in var_to_expand: add_var = pd.get_dummies(data[var], prefix=var, drop_first=True) # Add all the columns to the model data data = data.join(add_var) # Drop the original column that was expanded data.drop(columns=[var], inplace=True) self.preprocessed_data = data
python
def add_time_features(self, year=False, month=False, week=True, tod=True, dow=True): """ Add time features to dataframe. Parameters ---------- year : bool Year. month : bool Month. week : bool Week. tod : bool Time of Day. dow : bool Day of Week. """ var_to_expand = [] if self.preprocessed_data.empty: data = self.original_data else: data = self.preprocessed_data if year: data["year"] = data.index.year var_to_expand.append("year") if month: data["month"] = data.index.month var_to_expand.append("month") if week: data["week"] = data.index.week var_to_expand.append("week") if tod: data["tod"] = data.index.hour var_to_expand.append("tod") if dow: data["dow"] = data.index.weekday var_to_expand.append("dow") # One-hot encode the time features for var in var_to_expand: add_var = pd.get_dummies(data[var], prefix=var, drop_first=True) # Add all the columns to the model data data = data.join(add_var) # Drop the original column that was expanded data.drop(columns=[var], inplace=True) self.preprocessed_data = data
[ "def", "add_time_features", "(", "self", ",", "year", "=", "False", ",", "month", "=", "False", ",", "week", "=", "True", ",", "tod", "=", "True", ",", "dow", "=", "True", ")", ":", "var_to_expand", "=", "[", "]", "if", "self", ".", "preprocessed_data", ".", "empty", ":", "data", "=", "self", ".", "original_data", "else", ":", "data", "=", "self", ".", "preprocessed_data", "if", "year", ":", "data", "[", "\"year\"", "]", "=", "data", ".", "index", ".", "year", "var_to_expand", ".", "append", "(", "\"year\"", ")", "if", "month", ":", "data", "[", "\"month\"", "]", "=", "data", ".", "index", ".", "month", "var_to_expand", ".", "append", "(", "\"month\"", ")", "if", "week", ":", "data", "[", "\"week\"", "]", "=", "data", ".", "index", ".", "week", "var_to_expand", ".", "append", "(", "\"week\"", ")", "if", "tod", ":", "data", "[", "\"tod\"", "]", "=", "data", ".", "index", ".", "hour", "var_to_expand", ".", "append", "(", "\"tod\"", ")", "if", "dow", ":", "data", "[", "\"dow\"", "]", "=", "data", ".", "index", ".", "weekday", "var_to_expand", ".", "append", "(", "\"dow\"", ")", "# One-hot encode the time features", "for", "var", "in", "var_to_expand", ":", "add_var", "=", "pd", ".", "get_dummies", "(", "data", "[", "var", "]", ",", "prefix", "=", "var", ",", "drop_first", "=", "True", ")", "# Add all the columns to the model data", "data", "=", "data", ".", "join", "(", "add_var", ")", "# Drop the original column that was expanded", "data", ".", "drop", "(", "columns", "=", "[", "var", "]", ",", "inplace", "=", "True", ")", "self", ".", "preprocessed_data", "=", "data" ]
Add time features to dataframe. Parameters ---------- year : bool Year. month : bool Month. week : bool Week. tod : bool Time of Day. dow : bool Day of Week.
[ "Add", "time", "features", "to", "dataframe", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Preprocess_Data.py#L135-L187
2,064
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Model_Data.py
Model_Data.split_data
def split_data(self): """ Split data according to baseline and projection time period values. """ try: # Extract data ranging in time_period1 time_period1 = (slice(self.baseline_period[0], self.baseline_period[1])) self.baseline_in = self.original_data.loc[time_period1, self.input_col] self.baseline_out = self.original_data.loc[time_period1, self.output_col] if self.exclude_time_period: for i in range(0, len(self.exclude_time_period), 2): # Drop data ranging in exclude_time_period1 exclude_time_period1 = (slice(self.exclude_time_period[i], self.exclude_time_period[i+1])) self.baseline_in.drop(self.baseline_in.loc[exclude_time_period1].index, axis=0, inplace=True) self.baseline_out.drop(self.baseline_out.loc[exclude_time_period1].index, axis=0, inplace=True) except Exception as e: raise e # CHECK: Can optimize this part # Error checking to ensure time_period values are valid if self.projection_period: for i in range(0, len(self.projection_period), 2): period = (slice(self.projection_period[i], self.projection_period[i+1])) try: self.original_data.loc[period, self.input_col] self.original_data.loc[period, self.output_col] except Exception as e: raise e
python
def split_data(self): """ Split data according to baseline and projection time period values. """ try: # Extract data ranging in time_period1 time_period1 = (slice(self.baseline_period[0], self.baseline_period[1])) self.baseline_in = self.original_data.loc[time_period1, self.input_col] self.baseline_out = self.original_data.loc[time_period1, self.output_col] if self.exclude_time_period: for i in range(0, len(self.exclude_time_period), 2): # Drop data ranging in exclude_time_period1 exclude_time_period1 = (slice(self.exclude_time_period[i], self.exclude_time_period[i+1])) self.baseline_in.drop(self.baseline_in.loc[exclude_time_period1].index, axis=0, inplace=True) self.baseline_out.drop(self.baseline_out.loc[exclude_time_period1].index, axis=0, inplace=True) except Exception as e: raise e # CHECK: Can optimize this part # Error checking to ensure time_period values are valid if self.projection_period: for i in range(0, len(self.projection_period), 2): period = (slice(self.projection_period[i], self.projection_period[i+1])) try: self.original_data.loc[period, self.input_col] self.original_data.loc[period, self.output_col] except Exception as e: raise e
[ "def", "split_data", "(", "self", ")", ":", "try", ":", "# Extract data ranging in time_period1", "time_period1", "=", "(", "slice", "(", "self", ".", "baseline_period", "[", "0", "]", ",", "self", ".", "baseline_period", "[", "1", "]", ")", ")", "self", ".", "baseline_in", "=", "self", ".", "original_data", ".", "loc", "[", "time_period1", ",", "self", ".", "input_col", "]", "self", ".", "baseline_out", "=", "self", ".", "original_data", ".", "loc", "[", "time_period1", ",", "self", ".", "output_col", "]", "if", "self", ".", "exclude_time_period", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "exclude_time_period", ")", ",", "2", ")", ":", "# Drop data ranging in exclude_time_period1", "exclude_time_period1", "=", "(", "slice", "(", "self", ".", "exclude_time_period", "[", "i", "]", ",", "self", ".", "exclude_time_period", "[", "i", "+", "1", "]", ")", ")", "self", ".", "baseline_in", ".", "drop", "(", "self", ".", "baseline_in", ".", "loc", "[", "exclude_time_period1", "]", ".", "index", ",", "axis", "=", "0", ",", "inplace", "=", "True", ")", "self", ".", "baseline_out", ".", "drop", "(", "self", ".", "baseline_out", ".", "loc", "[", "exclude_time_period1", "]", ".", "index", ",", "axis", "=", "0", ",", "inplace", "=", "True", ")", "except", "Exception", "as", "e", ":", "raise", "e", "# CHECK: Can optimize this part", "# Error checking to ensure time_period values are valid", "if", "self", ".", "projection_period", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "projection_period", ")", ",", "2", ")", ":", "period", "=", "(", "slice", "(", "self", ".", "projection_period", "[", "i", "]", ",", "self", ".", "projection_period", "[", "i", "+", "1", "]", ")", ")", "try", ":", "self", ".", "original_data", ".", "loc", "[", "period", ",", "self", ".", "input_col", "]", "self", ".", "original_data", ".", "loc", "[", "period", ",", "self", ".", "output_col", "]", "except", "Exception", "as", "e", ":", "raise", "e" ]
Split data according to baseline and projection time period values.
[ "Split", "data", "according", "to", "baseline", "and", "projection", "time", "period", "values", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Model_Data.py#L125-L152
2,065
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Model_Data.py
Model_Data.linear_regression
def linear_regression(self): """ Linear Regression. This function runs linear regression and stores the, 1. Model 2. Model name 3. Mean score of cross validation 4. Metrics """ model = LinearRegression() scores = [] kfold = KFold(n_splits=self.cv, shuffle=True, random_state=42) for i, (train, test) in enumerate(kfold.split(self.baseline_in, self.baseline_out)): model.fit(self.baseline_in.iloc[train], self.baseline_out.iloc[train]) scores.append(model.score(self.baseline_in.iloc[test], self.baseline_out.iloc[test])) mean_score = sum(scores) / len(scores) self.models.append(model) self.model_names.append('Linear Regression') self.max_scores.append(mean_score) self.metrics['Linear Regression'] = {} self.metrics['Linear Regression']['R2'] = mean_score self.metrics['Linear Regression']['Adj R2'] = self.adj_r2(mean_score, self.baseline_in.shape[0], self.baseline_in.shape[1])
python
def linear_regression(self): """ Linear Regression. This function runs linear regression and stores the, 1. Model 2. Model name 3. Mean score of cross validation 4. Metrics """ model = LinearRegression() scores = [] kfold = KFold(n_splits=self.cv, shuffle=True, random_state=42) for i, (train, test) in enumerate(kfold.split(self.baseline_in, self.baseline_out)): model.fit(self.baseline_in.iloc[train], self.baseline_out.iloc[train]) scores.append(model.score(self.baseline_in.iloc[test], self.baseline_out.iloc[test])) mean_score = sum(scores) / len(scores) self.models.append(model) self.model_names.append('Linear Regression') self.max_scores.append(mean_score) self.metrics['Linear Regression'] = {} self.metrics['Linear Regression']['R2'] = mean_score self.metrics['Linear Regression']['Adj R2'] = self.adj_r2(mean_score, self.baseline_in.shape[0], self.baseline_in.shape[1])
[ "def", "linear_regression", "(", "self", ")", ":", "model", "=", "LinearRegression", "(", ")", "scores", "=", "[", "]", "kfold", "=", "KFold", "(", "n_splits", "=", "self", ".", "cv", ",", "shuffle", "=", "True", ",", "random_state", "=", "42", ")", "for", "i", ",", "(", "train", ",", "test", ")", "in", "enumerate", "(", "kfold", ".", "split", "(", "self", ".", "baseline_in", ",", "self", ".", "baseline_out", ")", ")", ":", "model", ".", "fit", "(", "self", ".", "baseline_in", ".", "iloc", "[", "train", "]", ",", "self", ".", "baseline_out", ".", "iloc", "[", "train", "]", ")", "scores", ".", "append", "(", "model", ".", "score", "(", "self", ".", "baseline_in", ".", "iloc", "[", "test", "]", ",", "self", ".", "baseline_out", ".", "iloc", "[", "test", "]", ")", ")", "mean_score", "=", "sum", "(", "scores", ")", "/", "len", "(", "scores", ")", "self", ".", "models", ".", "append", "(", "model", ")", "self", ".", "model_names", ".", "append", "(", "'Linear Regression'", ")", "self", ".", "max_scores", ".", "append", "(", "mean_score", ")", "self", ".", "metrics", "[", "'Linear Regression'", "]", "=", "{", "}", "self", ".", "metrics", "[", "'Linear Regression'", "]", "[", "'R2'", "]", "=", "mean_score", "self", ".", "metrics", "[", "'Linear Regression'", "]", "[", "'Adj R2'", "]", "=", "self", ".", "adj_r2", "(", "mean_score", ",", "self", ".", "baseline_in", ".", "shape", "[", "0", "]", ",", "self", ".", "baseline_in", ".", "shape", "[", "1", "]", ")" ]
Linear Regression. This function runs linear regression and stores the, 1. Model 2. Model name 3. Mean score of cross validation 4. Metrics
[ "Linear", "Regression", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Model_Data.py#L176-L203
2,066
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Model_Data.py
Model_Data.lasso_regression
def lasso_regression(self): """ Lasso Regression. This function runs lasso regression and stores the, 1. Model 2. Model name 3. Max score 4. Metrics """ score_list = [] max_score = float('-inf') best_alpha = None for alpha in self.alphas: # model = Lasso(normalize=True, alpha=alpha, max_iter=5000) model = Lasso(alpha=alpha, max_iter=5000) model.fit(self.baseline_in, self.baseline_out.values.ravel()) scores = [] kfold = KFold(n_splits=self.cv, shuffle=True, random_state=42) for i, (train, test) in enumerate(kfold.split(self.baseline_in, self.baseline_out)): model.fit(self.baseline_in.iloc[train], self.baseline_out.iloc[train]) scores.append(model.score(self.baseline_in.iloc[test], self.baseline_out.iloc[test])) mean_score = np.mean(scores) score_list.append(mean_score) if mean_score > max_score: max_score = mean_score best_alpha = alpha # self.models.append(Lasso(normalize=True, alpha=best_alpha, max_iter=5000)) self.models.append(Lasso(alpha=best_alpha, max_iter=5000)) self.model_names.append('Lasso Regression') self.max_scores.append(max_score) self.metrics['Lasso Regression'] = {} self.metrics['Lasso Regression']['R2'] = max_score self.metrics['Lasso Regression']['Adj R2'] = self.adj_r2(max_score, self.baseline_in.shape[0], self.baseline_in.shape[1])
python
def lasso_regression(self): """ Lasso Regression. This function runs lasso regression and stores the, 1. Model 2. Model name 3. Max score 4. Metrics """ score_list = [] max_score = float('-inf') best_alpha = None for alpha in self.alphas: # model = Lasso(normalize=True, alpha=alpha, max_iter=5000) model = Lasso(alpha=alpha, max_iter=5000) model.fit(self.baseline_in, self.baseline_out.values.ravel()) scores = [] kfold = KFold(n_splits=self.cv, shuffle=True, random_state=42) for i, (train, test) in enumerate(kfold.split(self.baseline_in, self.baseline_out)): model.fit(self.baseline_in.iloc[train], self.baseline_out.iloc[train]) scores.append(model.score(self.baseline_in.iloc[test], self.baseline_out.iloc[test])) mean_score = np.mean(scores) score_list.append(mean_score) if mean_score > max_score: max_score = mean_score best_alpha = alpha # self.models.append(Lasso(normalize=True, alpha=best_alpha, max_iter=5000)) self.models.append(Lasso(alpha=best_alpha, max_iter=5000)) self.model_names.append('Lasso Regression') self.max_scores.append(max_score) self.metrics['Lasso Regression'] = {} self.metrics['Lasso Regression']['R2'] = max_score self.metrics['Lasso Regression']['Adj R2'] = self.adj_r2(max_score, self.baseline_in.shape[0], self.baseline_in.shape[1])
[ "def", "lasso_regression", "(", "self", ")", ":", "score_list", "=", "[", "]", "max_score", "=", "float", "(", "'-inf'", ")", "best_alpha", "=", "None", "for", "alpha", "in", "self", ".", "alphas", ":", "# model = Lasso(normalize=True, alpha=alpha, max_iter=5000)", "model", "=", "Lasso", "(", "alpha", "=", "alpha", ",", "max_iter", "=", "5000", ")", "model", ".", "fit", "(", "self", ".", "baseline_in", ",", "self", ".", "baseline_out", ".", "values", ".", "ravel", "(", ")", ")", "scores", "=", "[", "]", "kfold", "=", "KFold", "(", "n_splits", "=", "self", ".", "cv", ",", "shuffle", "=", "True", ",", "random_state", "=", "42", ")", "for", "i", ",", "(", "train", ",", "test", ")", "in", "enumerate", "(", "kfold", ".", "split", "(", "self", ".", "baseline_in", ",", "self", ".", "baseline_out", ")", ")", ":", "model", ".", "fit", "(", "self", ".", "baseline_in", ".", "iloc", "[", "train", "]", ",", "self", ".", "baseline_out", ".", "iloc", "[", "train", "]", ")", "scores", ".", "append", "(", "model", ".", "score", "(", "self", ".", "baseline_in", ".", "iloc", "[", "test", "]", ",", "self", ".", "baseline_out", ".", "iloc", "[", "test", "]", ")", ")", "mean_score", "=", "np", ".", "mean", "(", "scores", ")", "score_list", ".", "append", "(", "mean_score", ")", "if", "mean_score", ">", "max_score", ":", "max_score", "=", "mean_score", "best_alpha", "=", "alpha", "# self.models.append(Lasso(normalize=True, alpha=best_alpha, max_iter=5000))", "self", ".", "models", ".", "append", "(", "Lasso", "(", "alpha", "=", "best_alpha", ",", "max_iter", "=", "5000", ")", ")", "self", ".", "model_names", ".", "append", "(", "'Lasso Regression'", ")", "self", ".", "max_scores", ".", "append", "(", "max_score", ")", "self", ".", "metrics", "[", "'Lasso Regression'", "]", "=", "{", "}", "self", ".", "metrics", "[", "'Lasso Regression'", "]", "[", "'R2'", "]", "=", "max_score", "self", ".", "metrics", "[", "'Lasso Regression'", "]", "[", "'Adj R2'", "]", "=", "self", ".", "adj_r2", "(", "max_score", ",", "self", ".", "baseline_in", ".", "shape", "[", "0", "]", ",", "self", ".", "baseline_in", ".", "shape", "[", "1", "]", ")" ]
Lasso Regression. This function runs lasso regression and stores the, 1. Model 2. Model name 3. Max score 4. Metrics
[ "Lasso", "Regression", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Model_Data.py#L206-L246
2,067
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Model_Data.py
Model_Data.random_forest
def random_forest(self): """ Random Forest. This function runs random forest and stores the, 1. Model 2. Model name 3. Max score 4. Metrics """ model = RandomForestRegressor(random_state=42) scores = [] kfold = KFold(n_splits=self.cv, shuffle=True, random_state=42) for i, (train, test) in enumerate(kfold.split(self.baseline_in, self.baseline_out)): model.fit(self.baseline_in.iloc[train], self.baseline_out.iloc[train]) scores.append(model.score(self.baseline_in.iloc[test], self.baseline_out.iloc[test])) mean_score = np.mean(scores) self.models.append(model) self.model_names.append('Random Forest Regressor') self.max_scores.append(mean_score) self.metrics['Random Forest Regressor'] = {} self.metrics['Random Forest Regressor']['R2'] = mean_score self.metrics['Random Forest Regressor']['Adj R2'] = self.adj_r2(mean_score, self.baseline_in.shape[0], self.baseline_in.shape[1])
python
def random_forest(self): """ Random Forest. This function runs random forest and stores the, 1. Model 2. Model name 3. Max score 4. Metrics """ model = RandomForestRegressor(random_state=42) scores = [] kfold = KFold(n_splits=self.cv, shuffle=True, random_state=42) for i, (train, test) in enumerate(kfold.split(self.baseline_in, self.baseline_out)): model.fit(self.baseline_in.iloc[train], self.baseline_out.iloc[train]) scores.append(model.score(self.baseline_in.iloc[test], self.baseline_out.iloc[test])) mean_score = np.mean(scores) self.models.append(model) self.model_names.append('Random Forest Regressor') self.max_scores.append(mean_score) self.metrics['Random Forest Regressor'] = {} self.metrics['Random Forest Regressor']['R2'] = mean_score self.metrics['Random Forest Regressor']['Adj R2'] = self.adj_r2(mean_score, self.baseline_in.shape[0], self.baseline_in.shape[1])
[ "def", "random_forest", "(", "self", ")", ":", "model", "=", "RandomForestRegressor", "(", "random_state", "=", "42", ")", "scores", "=", "[", "]", "kfold", "=", "KFold", "(", "n_splits", "=", "self", ".", "cv", ",", "shuffle", "=", "True", ",", "random_state", "=", "42", ")", "for", "i", ",", "(", "train", ",", "test", ")", "in", "enumerate", "(", "kfold", ".", "split", "(", "self", ".", "baseline_in", ",", "self", ".", "baseline_out", ")", ")", ":", "model", ".", "fit", "(", "self", ".", "baseline_in", ".", "iloc", "[", "train", "]", ",", "self", ".", "baseline_out", ".", "iloc", "[", "train", "]", ")", "scores", ".", "append", "(", "model", ".", "score", "(", "self", ".", "baseline_in", ".", "iloc", "[", "test", "]", ",", "self", ".", "baseline_out", ".", "iloc", "[", "test", "]", ")", ")", "mean_score", "=", "np", ".", "mean", "(", "scores", ")", "self", ".", "models", ".", "append", "(", "model", ")", "self", ".", "model_names", ".", "append", "(", "'Random Forest Regressor'", ")", "self", ".", "max_scores", ".", "append", "(", "mean_score", ")", "self", ".", "metrics", "[", "'Random Forest Regressor'", "]", "=", "{", "}", "self", ".", "metrics", "[", "'Random Forest Regressor'", "]", "[", "'R2'", "]", "=", "mean_score", "self", ".", "metrics", "[", "'Random Forest Regressor'", "]", "[", "'Adj R2'", "]", "=", "self", ".", "adj_r2", "(", "mean_score", ",", "self", ".", "baseline_in", ".", "shape", "[", "0", "]", ",", "self", ".", "baseline_in", ".", "shape", "[", "1", "]", ")" ]
Random Forest. This function runs random forest and stores the, 1. Model 2. Model name 3. Max score 4. Metrics
[ "Random", "Forest", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Model_Data.py#L338-L364
2,068
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Model_Data.py
Model_Data.run_models
def run_models(self): """ Run all models. Returns ------- model Best model dict Metrics of the models """ self.linear_regression() self.lasso_regression() self.ridge_regression() self.elastic_net_regression() self.random_forest() self.ann() # Index of the model with max score best_model_index = self.max_scores.index(max(self.max_scores)) # Store name of the optimal model self.best_model_name = self.model_names[best_model_index] # Store optimal model self.best_model = self.models[best_model_index] return self.metrics
python
def run_models(self): """ Run all models. Returns ------- model Best model dict Metrics of the models """ self.linear_regression() self.lasso_regression() self.ridge_regression() self.elastic_net_regression() self.random_forest() self.ann() # Index of the model with max score best_model_index = self.max_scores.index(max(self.max_scores)) # Store name of the optimal model self.best_model_name = self.model_names[best_model_index] # Store optimal model self.best_model = self.models[best_model_index] return self.metrics
[ "def", "run_models", "(", "self", ")", ":", "self", ".", "linear_regression", "(", ")", "self", ".", "lasso_regression", "(", ")", "self", ".", "ridge_regression", "(", ")", "self", ".", "elastic_net_regression", "(", ")", "self", ".", "random_forest", "(", ")", "self", ".", "ann", "(", ")", "# Index of the model with max score", "best_model_index", "=", "self", ".", "max_scores", ".", "index", "(", "max", "(", "self", ".", "max_scores", ")", ")", "# Store name of the optimal model", "self", ".", "best_model_name", "=", "self", ".", "model_names", "[", "best_model_index", "]", "# Store optimal model", "self", ".", "best_model", "=", "self", ".", "models", "[", "best_model_index", "]", "return", "self", ".", "metrics" ]
Run all models. Returns ------- model Best model dict Metrics of the models
[ "Run", "all", "models", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Model_Data.py#L396-L424
2,069
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Model_Data.py
Model_Data.custom_model
def custom_model(self, func): """ Run custom model provided by user. To Do, 1. Define custom function's parameters, its data types, and return types Parameters ---------- func : function Custom function Returns ------- dict Custom function's metrics """ y_pred = func(self.baseline_in, self.baseline_out) self.custom_metrics = {} self.custom_metrics['r2'] = r2_score(self.baseline_out, y_pred) self.custom_metrics['mse'] = mean_squared_error(self.baseline_out, y_pred) self.custom_metrics['rmse'] = math.sqrt(self.custom_metrics['mse']) self.custom_metrics['adj_r2'] = self.adj_r2(self.custom_metrics['r2'], self.baseline_in.shape[0], self.baseline_in.shape[1]) return self.custom_metrics
python
def custom_model(self, func): """ Run custom model provided by user. To Do, 1. Define custom function's parameters, its data types, and return types Parameters ---------- func : function Custom function Returns ------- dict Custom function's metrics """ y_pred = func(self.baseline_in, self.baseline_out) self.custom_metrics = {} self.custom_metrics['r2'] = r2_score(self.baseline_out, y_pred) self.custom_metrics['mse'] = mean_squared_error(self.baseline_out, y_pred) self.custom_metrics['rmse'] = math.sqrt(self.custom_metrics['mse']) self.custom_metrics['adj_r2'] = self.adj_r2(self.custom_metrics['r2'], self.baseline_in.shape[0], self.baseline_in.shape[1]) return self.custom_metrics
[ "def", "custom_model", "(", "self", ",", "func", ")", ":", "y_pred", "=", "func", "(", "self", ".", "baseline_in", ",", "self", ".", "baseline_out", ")", "self", ".", "custom_metrics", "=", "{", "}", "self", ".", "custom_metrics", "[", "'r2'", "]", "=", "r2_score", "(", "self", ".", "baseline_out", ",", "y_pred", ")", "self", ".", "custom_metrics", "[", "'mse'", "]", "=", "mean_squared_error", "(", "self", ".", "baseline_out", ",", "y_pred", ")", "self", ".", "custom_metrics", "[", "'rmse'", "]", "=", "math", ".", "sqrt", "(", "self", ".", "custom_metrics", "[", "'mse'", "]", ")", "self", ".", "custom_metrics", "[", "'adj_r2'", "]", "=", "self", ".", "adj_r2", "(", "self", ".", "custom_metrics", "[", "'r2'", "]", ",", "self", ".", "baseline_in", ".", "shape", "[", "0", "]", ",", "self", ".", "baseline_in", ".", "shape", "[", "1", "]", ")", "return", "self", ".", "custom_metrics" ]
Run custom model provided by user. To Do, 1. Define custom function's parameters, its data types, and return types Parameters ---------- func : function Custom function Returns ------- dict Custom function's metrics
[ "Run", "custom", "model", "provided", "by", "user", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Model_Data.py#L427-L453
2,070
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Model_Data.py
Model_Data.best_model_fit
def best_model_fit(self): """ Fit data to optimal model and return its metrics. Returns ------- dict Best model's metrics """ self.best_model.fit(self.baseline_in, self.baseline_out) self.y_true = self.baseline_out # Pandas Series self.y_pred = self.best_model.predict(self.baseline_in) # numpy.ndarray # Set all negative values to zero since energy > 0 self.y_pred[self.y_pred < 0] = 0 # n and k values for adj r2 score self.n_test = self.baseline_in.shape[0] # Number of points in data sample self.k_test = self.baseline_in.shape[1] # Number of variables in model, excluding the constant # Store best model's metrics self.best_metrics['name'] = self.best_model_name self.best_metrics['r2'] = r2_score(self.y_true, self.y_pred) self.best_metrics['mse'] = mean_squared_error(self.y_true, self.y_pred) self.best_metrics['rmse'] = math.sqrt(self.best_metrics['mse']) self.best_metrics['adj_r2'] = self.adj_r2(self.best_metrics['r2'], self.n_test, self.k_test) # Normalized Mean Bias Error numerator = sum(self.y_true - self.y_pred) denominator = (self.n_test - self.k_test) * (sum(self.y_true) / len(self.y_true)) self.best_metrics['nmbe'] = numerator / denominator # MAPE can't have 0 values in baseline_out -> divide by zero error self.baseline_out_copy = self.baseline_out[self.baseline_out != 0] self.baseline_in_copy = self.baseline_in[self.baseline_in.index.isin(self.baseline_out_copy.index)] self.y_true_copy = self.baseline_out_copy # Pandas Series self.y_pred_copy = self.best_model.predict(self.baseline_in_copy) # numpy.ndarray self.best_metrics['mape'] = np.mean(np.abs((self.y_true_copy - self.y_pred_copy) / self.y_true_copy)) * 100 return self.best_metrics
python
def best_model_fit(self): """ Fit data to optimal model and return its metrics. Returns ------- dict Best model's metrics """ self.best_model.fit(self.baseline_in, self.baseline_out) self.y_true = self.baseline_out # Pandas Series self.y_pred = self.best_model.predict(self.baseline_in) # numpy.ndarray # Set all negative values to zero since energy > 0 self.y_pred[self.y_pred < 0] = 0 # n and k values for adj r2 score self.n_test = self.baseline_in.shape[0] # Number of points in data sample self.k_test = self.baseline_in.shape[1] # Number of variables in model, excluding the constant # Store best model's metrics self.best_metrics['name'] = self.best_model_name self.best_metrics['r2'] = r2_score(self.y_true, self.y_pred) self.best_metrics['mse'] = mean_squared_error(self.y_true, self.y_pred) self.best_metrics['rmse'] = math.sqrt(self.best_metrics['mse']) self.best_metrics['adj_r2'] = self.adj_r2(self.best_metrics['r2'], self.n_test, self.k_test) # Normalized Mean Bias Error numerator = sum(self.y_true - self.y_pred) denominator = (self.n_test - self.k_test) * (sum(self.y_true) / len(self.y_true)) self.best_metrics['nmbe'] = numerator / denominator # MAPE can't have 0 values in baseline_out -> divide by zero error self.baseline_out_copy = self.baseline_out[self.baseline_out != 0] self.baseline_in_copy = self.baseline_in[self.baseline_in.index.isin(self.baseline_out_copy.index)] self.y_true_copy = self.baseline_out_copy # Pandas Series self.y_pred_copy = self.best_model.predict(self.baseline_in_copy) # numpy.ndarray self.best_metrics['mape'] = np.mean(np.abs((self.y_true_copy - self.y_pred_copy) / self.y_true_copy)) * 100 return self.best_metrics
[ "def", "best_model_fit", "(", "self", ")", ":", "self", ".", "best_model", ".", "fit", "(", "self", ".", "baseline_in", ",", "self", ".", "baseline_out", ")", "self", ".", "y_true", "=", "self", ".", "baseline_out", "# Pandas Series", "self", ".", "y_pred", "=", "self", ".", "best_model", ".", "predict", "(", "self", ".", "baseline_in", ")", "# numpy.ndarray", "# Set all negative values to zero since energy > 0", "self", ".", "y_pred", "[", "self", ".", "y_pred", "<", "0", "]", "=", "0", "# n and k values for adj r2 score", "self", ".", "n_test", "=", "self", ".", "baseline_in", ".", "shape", "[", "0", "]", "# Number of points in data sample", "self", ".", "k_test", "=", "self", ".", "baseline_in", ".", "shape", "[", "1", "]", "# Number of variables in model, excluding the constant", "# Store best model's metrics", "self", ".", "best_metrics", "[", "'name'", "]", "=", "self", ".", "best_model_name", "self", ".", "best_metrics", "[", "'r2'", "]", "=", "r2_score", "(", "self", ".", "y_true", ",", "self", ".", "y_pred", ")", "self", ".", "best_metrics", "[", "'mse'", "]", "=", "mean_squared_error", "(", "self", ".", "y_true", ",", "self", ".", "y_pred", ")", "self", ".", "best_metrics", "[", "'rmse'", "]", "=", "math", ".", "sqrt", "(", "self", ".", "best_metrics", "[", "'mse'", "]", ")", "self", ".", "best_metrics", "[", "'adj_r2'", "]", "=", "self", ".", "adj_r2", "(", "self", ".", "best_metrics", "[", "'r2'", "]", ",", "self", ".", "n_test", ",", "self", ".", "k_test", ")", "# Normalized Mean Bias Error", "numerator", "=", "sum", "(", "self", ".", "y_true", "-", "self", ".", "y_pred", ")", "denominator", "=", "(", "self", ".", "n_test", "-", "self", ".", "k_test", ")", "*", "(", "sum", "(", "self", ".", "y_true", ")", "/", "len", "(", "self", ".", "y_true", ")", ")", "self", ".", "best_metrics", "[", "'nmbe'", "]", "=", "numerator", "/", "denominator", "# MAPE can't have 0 values in baseline_out -> divide by zero error", "self", ".", "baseline_out_copy", "=", "self", ".", "baseline_out", "[", "self", ".", "baseline_out", "!=", "0", "]", "self", ".", "baseline_in_copy", "=", "self", ".", "baseline_in", "[", "self", ".", "baseline_in", ".", "index", ".", "isin", "(", "self", ".", "baseline_out_copy", ".", "index", ")", "]", "self", ".", "y_true_copy", "=", "self", ".", "baseline_out_copy", "# Pandas Series", "self", ".", "y_pred_copy", "=", "self", ".", "best_model", ".", "predict", "(", "self", ".", "baseline_in_copy", ")", "# numpy.ndarray", "self", ".", "best_metrics", "[", "'mape'", "]", "=", "np", ".", "mean", "(", "np", ".", "abs", "(", "(", "self", ".", "y_true_copy", "-", "self", ".", "y_pred_copy", ")", "/", "self", ".", "y_true_copy", ")", ")", "*", "100", "return", "self", ".", "best_metrics" ]
Fit data to optimal model and return its metrics. Returns ------- dict Best model's metrics
[ "Fit", "data", "to", "optimal", "model", "and", "return", "its", "metrics", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Model_Data.py#L456-L497
2,071
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Plot_Data.py
Plot_Data.correlation_plot
def correlation_plot(self, data): """ Create heatmap of Pearson's correlation coefficient. Parameters ---------- data : pd.DataFrame() Data to display. Returns ------- matplotlib.figure Heatmap. """ # CHECK: Add saved filename in result.json fig = plt.figure(Plot_Data.count) corr = data.corr() ax = sns.heatmap(corr) Plot_Data.count += 1 return fig
python
def correlation_plot(self, data): """ Create heatmap of Pearson's correlation coefficient. Parameters ---------- data : pd.DataFrame() Data to display. Returns ------- matplotlib.figure Heatmap. """ # CHECK: Add saved filename in result.json fig = plt.figure(Plot_Data.count) corr = data.corr() ax = sns.heatmap(corr) Plot_Data.count += 1 return fig
[ "def", "correlation_plot", "(", "self", ",", "data", ")", ":", "# CHECK: Add saved filename in result.json", "fig", "=", "plt", ".", "figure", "(", "Plot_Data", ".", "count", ")", "corr", "=", "data", ".", "corr", "(", ")", "ax", "=", "sns", ".", "heatmap", "(", "corr", ")", "Plot_Data", ".", "count", "+=", "1", "return", "fig" ]
Create heatmap of Pearson's correlation coefficient. Parameters ---------- data : pd.DataFrame() Data to display. Returns ------- matplotlib.figure Heatmap.
[ "Create", "heatmap", "of", "Pearson", "s", "correlation", "coefficient", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Plot_Data.py#L42-L63
2,072
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Plot_Data.py
Plot_Data.baseline_projection_plot
def baseline_projection_plot(self, y_true, y_pred, baseline_period, projection_period, model_name, adj_r2, data, input_col, output_col, model, site): """ Create baseline and projection plots. Parameters ---------- y_true : pd.Series() Actual y values. y_pred : np.ndarray Predicted y values. baseline_period : list(str) Baseline period. projection_period : list(str) Projection periods. model_name : str Optimal model's name. adj_r2 : float Adjusted R2 score of optimal model. data : pd.Dataframe() Data containing real values. input_col : list(str) Predictor column(s). output_col : str Target column. model : func Optimal model. Returns ------- matplotlib.figure Baseline plot """ # Baseline and projection plots fig = plt.figure(Plot_Data.count) # Number of plots to display if projection_period: nrows = len(baseline_period) + len(projection_period) / 2 else: nrows = len(baseline_period) / 2 # Plot 1 - Baseline base_df = pd.DataFrame() base_df['y_true'] = y_true base_df['y_pred'] = y_pred ax1 = fig.add_subplot(nrows, 1, 1) base_df.plot(ax=ax1, figsize=self.figsize, title='Baseline Period ({}-{}). \nBest Model: {}. \nBaseline Adj R2: {}. \nSite: {}.'.format(baseline_period[0], baseline_period[1], model_name, adj_r2, site)) if projection_period: # Display projection plots num_plot = 2 for i in range(0, len(projection_period), 2): ax = fig.add_subplot(nrows, 1, num_plot) period = (slice(projection_period[i], projection_period[i+1])) project_df = pd.DataFrame() try: project_df['y_true'] = data.loc[period, output_col] project_df['y_pred'] = model.predict(data.loc[period, input_col]) # Set all negative values to zero since energy > 0 project_df['y_pred'][project_df['y_pred'] < 0] = 0 project_df.plot(ax=ax, figsize=self.figsize, title='Projection Period ({}-{})'.format(projection_period[i], projection_period[i+1])) num_plot += 1 fig.tight_layout() Plot_Data.count += 1 return fig, project_df['y_true'], project_df['y_pred'] except: raise TypeError("If projecting into the future, please specify project_ind_col that has data available \ in the future time period requested.") return fig, None, None
python
def baseline_projection_plot(self, y_true, y_pred, baseline_period, projection_period, model_name, adj_r2, data, input_col, output_col, model, site): """ Create baseline and projection plots. Parameters ---------- y_true : pd.Series() Actual y values. y_pred : np.ndarray Predicted y values. baseline_period : list(str) Baseline period. projection_period : list(str) Projection periods. model_name : str Optimal model's name. adj_r2 : float Adjusted R2 score of optimal model. data : pd.Dataframe() Data containing real values. input_col : list(str) Predictor column(s). output_col : str Target column. model : func Optimal model. Returns ------- matplotlib.figure Baseline plot """ # Baseline and projection plots fig = plt.figure(Plot_Data.count) # Number of plots to display if projection_period: nrows = len(baseline_period) + len(projection_period) / 2 else: nrows = len(baseline_period) / 2 # Plot 1 - Baseline base_df = pd.DataFrame() base_df['y_true'] = y_true base_df['y_pred'] = y_pred ax1 = fig.add_subplot(nrows, 1, 1) base_df.plot(ax=ax1, figsize=self.figsize, title='Baseline Period ({}-{}). \nBest Model: {}. \nBaseline Adj R2: {}. \nSite: {}.'.format(baseline_period[0], baseline_period[1], model_name, adj_r2, site)) if projection_period: # Display projection plots num_plot = 2 for i in range(0, len(projection_period), 2): ax = fig.add_subplot(nrows, 1, num_plot) period = (slice(projection_period[i], projection_period[i+1])) project_df = pd.DataFrame() try: project_df['y_true'] = data.loc[period, output_col] project_df['y_pred'] = model.predict(data.loc[period, input_col]) # Set all negative values to zero since energy > 0 project_df['y_pred'][project_df['y_pred'] < 0] = 0 project_df.plot(ax=ax, figsize=self.figsize, title='Projection Period ({}-{})'.format(projection_period[i], projection_period[i+1])) num_plot += 1 fig.tight_layout() Plot_Data.count += 1 return fig, project_df['y_true'], project_df['y_pred'] except: raise TypeError("If projecting into the future, please specify project_ind_col that has data available \ in the future time period requested.") return fig, None, None
[ "def", "baseline_projection_plot", "(", "self", ",", "y_true", ",", "y_pred", ",", "baseline_period", ",", "projection_period", ",", "model_name", ",", "adj_r2", ",", "data", ",", "input_col", ",", "output_col", ",", "model", ",", "site", ")", ":", "# Baseline and projection plots", "fig", "=", "plt", ".", "figure", "(", "Plot_Data", ".", "count", ")", "# Number of plots to display", "if", "projection_period", ":", "nrows", "=", "len", "(", "baseline_period", ")", "+", "len", "(", "projection_period", ")", "/", "2", "else", ":", "nrows", "=", "len", "(", "baseline_period", ")", "/", "2", "# Plot 1 - Baseline", "base_df", "=", "pd", ".", "DataFrame", "(", ")", "base_df", "[", "'y_true'", "]", "=", "y_true", "base_df", "[", "'y_pred'", "]", "=", "y_pred", "ax1", "=", "fig", ".", "add_subplot", "(", "nrows", ",", "1", ",", "1", ")", "base_df", ".", "plot", "(", "ax", "=", "ax1", ",", "figsize", "=", "self", ".", "figsize", ",", "title", "=", "'Baseline Period ({}-{}). \\nBest Model: {}. \\nBaseline Adj R2: {}. \\nSite: {}.'", ".", "format", "(", "baseline_period", "[", "0", "]", ",", "baseline_period", "[", "1", "]", ",", "model_name", ",", "adj_r2", ",", "site", ")", ")", "if", "projection_period", ":", "# Display projection plots", "num_plot", "=", "2", "for", "i", "in", "range", "(", "0", ",", "len", "(", "projection_period", ")", ",", "2", ")", ":", "ax", "=", "fig", ".", "add_subplot", "(", "nrows", ",", "1", ",", "num_plot", ")", "period", "=", "(", "slice", "(", "projection_period", "[", "i", "]", ",", "projection_period", "[", "i", "+", "1", "]", ")", ")", "project_df", "=", "pd", ".", "DataFrame", "(", ")", "try", ":", "project_df", "[", "'y_true'", "]", "=", "data", ".", "loc", "[", "period", ",", "output_col", "]", "project_df", "[", "'y_pred'", "]", "=", "model", ".", "predict", "(", "data", ".", "loc", "[", "period", ",", "input_col", "]", ")", "# Set all negative values to zero since energy > 0", "project_df", "[", "'y_pred'", "]", "[", "project_df", "[", "'y_pred'", "]", "<", "0", "]", "=", "0", "project_df", ".", "plot", "(", "ax", "=", "ax", ",", "figsize", "=", "self", ".", "figsize", ",", "title", "=", "'Projection Period ({}-{})'", ".", "format", "(", "projection_period", "[", "i", "]", ",", "projection_period", "[", "i", "+", "1", "]", ")", ")", "num_plot", "+=", "1", "fig", ".", "tight_layout", "(", ")", "Plot_Data", ".", "count", "+=", "1", "return", "fig", ",", "project_df", "[", "'y_true'", "]", ",", "project_df", "[", "'y_pred'", "]", "except", ":", "raise", "TypeError", "(", "\"If projecting into the future, please specify project_ind_col that has data available \\\n in the future time period requested.\"", ")", "return", "fig", ",", "None", ",", "None" ]
Create baseline and projection plots. Parameters ---------- y_true : pd.Series() Actual y values. y_pred : np.ndarray Predicted y values. baseline_period : list(str) Baseline period. projection_period : list(str) Projection periods. model_name : str Optimal model's name. adj_r2 : float Adjusted R2 score of optimal model. data : pd.Dataframe() Data containing real values. input_col : list(str) Predictor column(s). output_col : str Target column. model : func Optimal model. Returns ------- matplotlib.figure Baseline plot
[ "Create", "baseline", "and", "projection", "plots", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Plot_Data.py#L66-L147
2,073
SoftwareDefinedBuildings/XBOS
apps/system_identification/rtu_energy.py
get_thermostat_meter_data
def get_thermostat_meter_data(zone): """ This method subscribes to the output of the meter for the given zone. It returns a handler to call when you want to stop subscribing data, which returns a list of the data readins over that time period """ meter_uri = zone2meter.get(zone, "None") data = [] def cb(msg): for po in msg.payload_objects: if po.type_dotted == (2,0,9,1): m = msgpack.unpackb(po.content) data.append(m['current_demand']) handle = c.subscribe(meter_uri+"/signal/meter", cb) def stop(): c.unsubscribe(handle) return data return stop
python
def get_thermostat_meter_data(zone): """ This method subscribes to the output of the meter for the given zone. It returns a handler to call when you want to stop subscribing data, which returns a list of the data readins over that time period """ meter_uri = zone2meter.get(zone, "None") data = [] def cb(msg): for po in msg.payload_objects: if po.type_dotted == (2,0,9,1): m = msgpack.unpackb(po.content) data.append(m['current_demand']) handle = c.subscribe(meter_uri+"/signal/meter", cb) def stop(): c.unsubscribe(handle) return data return stop
[ "def", "get_thermostat_meter_data", "(", "zone", ")", ":", "meter_uri", "=", "zone2meter", ".", "get", "(", "zone", ",", "\"None\"", ")", "data", "=", "[", "]", "def", "cb", "(", "msg", ")", ":", "for", "po", "in", "msg", ".", "payload_objects", ":", "if", "po", ".", "type_dotted", "==", "(", "2", ",", "0", ",", "9", ",", "1", ")", ":", "m", "=", "msgpack", ".", "unpackb", "(", "po", ".", "content", ")", "data", ".", "append", "(", "m", "[", "'current_demand'", "]", ")", "handle", "=", "c", ".", "subscribe", "(", "meter_uri", "+", "\"/signal/meter\"", ",", "cb", ")", "def", "stop", "(", ")", ":", "c", ".", "unsubscribe", "(", "handle", ")", "return", "data", "return", "stop" ]
This method subscribes to the output of the meter for the given zone. It returns a handler to call when you want to stop subscribing data, which returns a list of the data readins over that time period
[ "This", "method", "subscribes", "to", "the", "output", "of", "the", "meter", "for", "the", "given", "zone", ".", "It", "returns", "a", "handler", "to", "call", "when", "you", "want", "to", "stop", "subscribing", "data", "which", "returns", "a", "list", "of", "the", "data", "readins", "over", "that", "time", "period" ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/system_identification/rtu_energy.py#L53-L71
2,074
SoftwareDefinedBuildings/XBOS
apps/system_identification/rtu_energy.py
call_heat
def call_heat(tstat): """ Adjusts the temperature setpoints in order to call for heating. Returns a handler to call when you want to reset the thermostat """ current_hsp, current_csp = tstat.heating_setpoint, tstat.cooling_setpoint current_temp = tstat.temperature tstat.write({ 'heating_setpoint': current_temp+10, 'cooling_setpoint': current_temp+20, 'mode': HEAT, }) def restore(): tstat.write({ 'heating_setpoint': current_hsp, 'cooling_setpoint': current_csp, 'mode': AUTO, }) return restore
python
def call_heat(tstat): """ Adjusts the temperature setpoints in order to call for heating. Returns a handler to call when you want to reset the thermostat """ current_hsp, current_csp = tstat.heating_setpoint, tstat.cooling_setpoint current_temp = tstat.temperature tstat.write({ 'heating_setpoint': current_temp+10, 'cooling_setpoint': current_temp+20, 'mode': HEAT, }) def restore(): tstat.write({ 'heating_setpoint': current_hsp, 'cooling_setpoint': current_csp, 'mode': AUTO, }) return restore
[ "def", "call_heat", "(", "tstat", ")", ":", "current_hsp", ",", "current_csp", "=", "tstat", ".", "heating_setpoint", ",", "tstat", ".", "cooling_setpoint", "current_temp", "=", "tstat", ".", "temperature", "tstat", ".", "write", "(", "{", "'heating_setpoint'", ":", "current_temp", "+", "10", ",", "'cooling_setpoint'", ":", "current_temp", "+", "20", ",", "'mode'", ":", "HEAT", ",", "}", ")", "def", "restore", "(", ")", ":", "tstat", ".", "write", "(", "{", "'heating_setpoint'", ":", "current_hsp", ",", "'cooling_setpoint'", ":", "current_csp", ",", "'mode'", ":", "AUTO", ",", "}", ")", "return", "restore" ]
Adjusts the temperature setpoints in order to call for heating. Returns a handler to call when you want to reset the thermostat
[ "Adjusts", "the", "temperature", "setpoints", "in", "order", "to", "call", "for", "heating", ".", "Returns", "a", "handler", "to", "call", "when", "you", "want", "to", "reset", "the", "thermostat" ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/system_identification/rtu_energy.py#L73-L92
2,075
SoftwareDefinedBuildings/XBOS
apps/system_identification/rtu_energy.py
call_cool
def call_cool(tstat): """ Adjusts the temperature setpoints in order to call for cooling. Returns a handler to call when you want to reset the thermostat """ current_hsp, current_csp = tstat.heating_setpoint, tstat.cooling_setpoint current_temp = tstat.temperature tstat.write({ 'heating_setpoint': current_temp-20, 'cooling_setpoint': current_temp-10, 'mode': COOL, }) def restore(): tstat.write({ 'heating_setpoint': current_hsp, 'cooling_setpoint': current_csp, 'mode': AUTO, }) return restore
python
def call_cool(tstat): """ Adjusts the temperature setpoints in order to call for cooling. Returns a handler to call when you want to reset the thermostat """ current_hsp, current_csp = tstat.heating_setpoint, tstat.cooling_setpoint current_temp = tstat.temperature tstat.write({ 'heating_setpoint': current_temp-20, 'cooling_setpoint': current_temp-10, 'mode': COOL, }) def restore(): tstat.write({ 'heating_setpoint': current_hsp, 'cooling_setpoint': current_csp, 'mode': AUTO, }) return restore
[ "def", "call_cool", "(", "tstat", ")", ":", "current_hsp", ",", "current_csp", "=", "tstat", ".", "heating_setpoint", ",", "tstat", ".", "cooling_setpoint", "current_temp", "=", "tstat", ".", "temperature", "tstat", ".", "write", "(", "{", "'heating_setpoint'", ":", "current_temp", "-", "20", ",", "'cooling_setpoint'", ":", "current_temp", "-", "10", ",", "'mode'", ":", "COOL", ",", "}", ")", "def", "restore", "(", ")", ":", "tstat", ".", "write", "(", "{", "'heating_setpoint'", ":", "current_hsp", ",", "'cooling_setpoint'", ":", "current_csp", ",", "'mode'", ":", "AUTO", ",", "}", ")", "return", "restore" ]
Adjusts the temperature setpoints in order to call for cooling. Returns a handler to call when you want to reset the thermostat
[ "Adjusts", "the", "temperature", "setpoints", "in", "order", "to", "call", "for", "cooling", ".", "Returns", "a", "handler", "to", "call", "when", "you", "want", "to", "reset", "the", "thermostat" ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/system_identification/rtu_energy.py#L94-L113
2,076
SoftwareDefinedBuildings/XBOS
apps/system_identification/rtu_energy.py
call_fan
def call_fan(tstat): """ Toggles the fan """ old_fan = tstat.fan tstat.write({ 'fan': not old_fan, }) def restore(): tstat.write({ 'fan': old_fan, }) return restore
python
def call_fan(tstat): """ Toggles the fan """ old_fan = tstat.fan tstat.write({ 'fan': not old_fan, }) def restore(): tstat.write({ 'fan': old_fan, }) return restore
[ "def", "call_fan", "(", "tstat", ")", ":", "old_fan", "=", "tstat", ".", "fan", "tstat", ".", "write", "(", "{", "'fan'", ":", "not", "old_fan", ",", "}", ")", "def", "restore", "(", ")", ":", "tstat", ".", "write", "(", "{", "'fan'", ":", "old_fan", ",", "}", ")", "return", "restore" ]
Toggles the fan
[ "Toggles", "the", "fan" ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/system_identification/rtu_energy.py#L115-L129
2,077
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Import_Data.py
Import_Data._load_csv
def _load_csv(self, file_name, folder_name, head_row, index_col, convert_col, concat_files): """ Load single csv file. Parameters ---------- file_name : str CSV file to be imported. Defaults to '*' - all csv files in the folder. folder_name : str Folder where file resides. Defaults to '.' - current directory. head_row : int Skips all rows from 0 to head_row-1 index_col : int Skips all columns from 0 to index_col-1 convert_col : bool Convert columns to numeric type concat_files : bool Appends data from files to result dataframe Returns ------- pd.DataFrame() Dataframe containing csv data """ # Denotes all csv files if file_name == "*": if not os.path.isdir(folder_name): raise OSError('Folder does not exist.') else: file_name_list = sorted(glob.glob(folder_name + '*.csv')) if not file_name_list: raise OSError('Either the folder does not contain any csv files or invalid folder provided.') else: # Call previous function again with parameters changed (file_name=file_name_list, folder_name=None) # Done to reduce redundancy of code self.import_csv(file_name=file_name_list, head_row=head_row, index_col=index_col, convert_col=convert_col, concat_files=concat_files) return self.data else: if not os.path.isdir(folder_name): raise OSError('Folder does not exist.') else: path = os.path.join(folder_name, file_name) if head_row > 0: data = pd.read_csv(path, index_col=index_col, skiprows=[i for i in range(head_row-1)]) else: data = pd.read_csv(path, index_col=index_col) # Convert time into datetime format try: # Special case format 1/4/14 21:30 data.index = pd.to_datetime(data.index, format='%m/%d/%y %H:%M') except: data.index = pd.to_datetime(data.index, dayfirst=False, infer_datetime_format=True) # Convert all columns to numeric type if convert_col: # Check columns in dataframe to see if they are numeric for col in data.columns: # If particular column is not numeric, then convert to numeric type if data[col].dtype != np.number: data[col] = pd.to_numeric(data[col], errors="coerce") return data
python
def _load_csv(self, file_name, folder_name, head_row, index_col, convert_col, concat_files): """ Load single csv file. Parameters ---------- file_name : str CSV file to be imported. Defaults to '*' - all csv files in the folder. folder_name : str Folder where file resides. Defaults to '.' - current directory. head_row : int Skips all rows from 0 to head_row-1 index_col : int Skips all columns from 0 to index_col-1 convert_col : bool Convert columns to numeric type concat_files : bool Appends data from files to result dataframe Returns ------- pd.DataFrame() Dataframe containing csv data """ # Denotes all csv files if file_name == "*": if not os.path.isdir(folder_name): raise OSError('Folder does not exist.') else: file_name_list = sorted(glob.glob(folder_name + '*.csv')) if not file_name_list: raise OSError('Either the folder does not contain any csv files or invalid folder provided.') else: # Call previous function again with parameters changed (file_name=file_name_list, folder_name=None) # Done to reduce redundancy of code self.import_csv(file_name=file_name_list, head_row=head_row, index_col=index_col, convert_col=convert_col, concat_files=concat_files) return self.data else: if not os.path.isdir(folder_name): raise OSError('Folder does not exist.') else: path = os.path.join(folder_name, file_name) if head_row > 0: data = pd.read_csv(path, index_col=index_col, skiprows=[i for i in range(head_row-1)]) else: data = pd.read_csv(path, index_col=index_col) # Convert time into datetime format try: # Special case format 1/4/14 21:30 data.index = pd.to_datetime(data.index, format='%m/%d/%y %H:%M') except: data.index = pd.to_datetime(data.index, dayfirst=False, infer_datetime_format=True) # Convert all columns to numeric type if convert_col: # Check columns in dataframe to see if they are numeric for col in data.columns: # If particular column is not numeric, then convert to numeric type if data[col].dtype != np.number: data[col] = pd.to_numeric(data[col], errors="coerce") return data
[ "def", "_load_csv", "(", "self", ",", "file_name", ",", "folder_name", ",", "head_row", ",", "index_col", ",", "convert_col", ",", "concat_files", ")", ":", "# Denotes all csv files", "if", "file_name", "==", "\"*\"", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "folder_name", ")", ":", "raise", "OSError", "(", "'Folder does not exist.'", ")", "else", ":", "file_name_list", "=", "sorted", "(", "glob", ".", "glob", "(", "folder_name", "+", "'*.csv'", ")", ")", "if", "not", "file_name_list", ":", "raise", "OSError", "(", "'Either the folder does not contain any csv files or invalid folder provided.'", ")", "else", ":", "# Call previous function again with parameters changed (file_name=file_name_list, folder_name=None)", "# Done to reduce redundancy of code", "self", ".", "import_csv", "(", "file_name", "=", "file_name_list", ",", "head_row", "=", "head_row", ",", "index_col", "=", "index_col", ",", "convert_col", "=", "convert_col", ",", "concat_files", "=", "concat_files", ")", "return", "self", ".", "data", "else", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "folder_name", ")", ":", "raise", "OSError", "(", "'Folder does not exist.'", ")", "else", ":", "path", "=", "os", ".", "path", ".", "join", "(", "folder_name", ",", "file_name", ")", "if", "head_row", ">", "0", ":", "data", "=", "pd", ".", "read_csv", "(", "path", ",", "index_col", "=", "index_col", ",", "skiprows", "=", "[", "i", "for", "i", "in", "range", "(", "head_row", "-", "1", ")", "]", ")", "else", ":", "data", "=", "pd", ".", "read_csv", "(", "path", ",", "index_col", "=", "index_col", ")", "# Convert time into datetime format", "try", ":", "# Special case format 1/4/14 21:30", "data", ".", "index", "=", "pd", ".", "to_datetime", "(", "data", ".", "index", ",", "format", "=", "'%m/%d/%y %H:%M'", ")", "except", ":", "data", ".", "index", "=", "pd", ".", "to_datetime", "(", "data", ".", "index", ",", "dayfirst", "=", "False", ",", "infer_datetime_format", "=", "True", ")", "# Convert all columns to numeric type", "if", "convert_col", ":", "# Check columns in dataframe to see if they are numeric", "for", "col", "in", "data", ".", "columns", ":", "# If particular column is not numeric, then convert to numeric type", "if", "data", "[", "col", "]", ".", "dtype", "!=", "np", ".", "number", ":", "data", "[", "col", "]", "=", "pd", ".", "to_numeric", "(", "data", "[", "col", "]", ",", "errors", "=", "\"coerce\"", ")", "return", "data" ]
Load single csv file. Parameters ---------- file_name : str CSV file to be imported. Defaults to '*' - all csv files in the folder. folder_name : str Folder where file resides. Defaults to '.' - current directory. head_row : int Skips all rows from 0 to head_row-1 index_col : int Skips all columns from 0 to index_col-1 convert_col : bool Convert columns to numeric type concat_files : bool Appends data from files to result dataframe Returns ------- pd.DataFrame() Dataframe containing csv data
[ "Load", "single", "csv", "file", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Import_Data.py#L106-L174
2,078
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Import_Data.py
Import_MDAL.convert_to_utc
def convert_to_utc(time): """ Convert time to UTC Parameters ---------- time : str Time to convert. Has to be of the format '2016-01-01T00:00:00-08:00'. Returns ------- str UTC timestamp. """ # time is already in UTC if 'Z' in time: return time else: time_formatted = time[:-3] + time[-2:] dt = datetime.strptime(time_formatted, '%Y-%m-%dT%H:%M:%S%z') dt = dt.astimezone(timezone('UTC')) return dt.strftime('%Y-%m-%dT%H:%M:%SZ')
python
def convert_to_utc(time): """ Convert time to UTC Parameters ---------- time : str Time to convert. Has to be of the format '2016-01-01T00:00:00-08:00'. Returns ------- str UTC timestamp. """ # time is already in UTC if 'Z' in time: return time else: time_formatted = time[:-3] + time[-2:] dt = datetime.strptime(time_formatted, '%Y-%m-%dT%H:%M:%S%z') dt = dt.astimezone(timezone('UTC')) return dt.strftime('%Y-%m-%dT%H:%M:%SZ')
[ "def", "convert_to_utc", "(", "time", ")", ":", "# time is already in UTC", "if", "'Z'", "in", "time", ":", "return", "time", "else", ":", "time_formatted", "=", "time", "[", ":", "-", "3", "]", "+", "time", "[", "-", "2", ":", "]", "dt", "=", "datetime", ".", "strptime", "(", "time_formatted", ",", "'%Y-%m-%dT%H:%M:%S%z'", ")", "dt", "=", "dt", ".", "astimezone", "(", "timezone", "(", "'UTC'", ")", ")", "return", "dt", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")" ]
Convert time to UTC Parameters ---------- time : str Time to convert. Has to be of the format '2016-01-01T00:00:00-08:00'. Returns ------- str UTC timestamp.
[ "Convert", "time", "to", "UTC" ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Import_Data.py#L190-L212
2,079
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Import_Data.py
Import_MDAL.get_meter
def get_meter(self, site, start, end, point_type='Green_Button_Meter', var="meter", agg='MEAN', window='24h', aligned=True, return_names=True): """ Get meter data from MDAL. Parameters ---------- site : str Building name. start : str Start date - 'YYYY-MM-DDTHH:MM:SSZ' end : str End date - 'YYYY-MM-DDTHH:MM:SSZ' point_type : str Type of data, i.e. Green_Button_Meter, Building_Electric_Meter... var : str Variable - "meter", "weather"... agg : str Aggregation - MEAN, SUM, RAW... window : str Size of the moving window. aligned : bool ??? return_names : bool ??? Returns ------- (df, mapping, context) ??? """ # Convert time to UTC start = self.convert_to_utc(start) end = self.convert_to_utc(end) request = self.compose_MDAL_dic(point_type=point_type, site=site, start=start, end=end, var=var, agg=agg, window=window, aligned=aligned) resp = self.m.query(request) if return_names: resp = self.replace_uuid_w_names(resp) return resp
python
def get_meter(self, site, start, end, point_type='Green_Button_Meter', var="meter", agg='MEAN', window='24h', aligned=True, return_names=True): """ Get meter data from MDAL. Parameters ---------- site : str Building name. start : str Start date - 'YYYY-MM-DDTHH:MM:SSZ' end : str End date - 'YYYY-MM-DDTHH:MM:SSZ' point_type : str Type of data, i.e. Green_Button_Meter, Building_Electric_Meter... var : str Variable - "meter", "weather"... agg : str Aggregation - MEAN, SUM, RAW... window : str Size of the moving window. aligned : bool ??? return_names : bool ??? Returns ------- (df, mapping, context) ??? """ # Convert time to UTC start = self.convert_to_utc(start) end = self.convert_to_utc(end) request = self.compose_MDAL_dic(point_type=point_type, site=site, start=start, end=end, var=var, agg=agg, window=window, aligned=aligned) resp = self.m.query(request) if return_names: resp = self.replace_uuid_w_names(resp) return resp
[ "def", "get_meter", "(", "self", ",", "site", ",", "start", ",", "end", ",", "point_type", "=", "'Green_Button_Meter'", ",", "var", "=", "\"meter\"", ",", "agg", "=", "'MEAN'", ",", "window", "=", "'24h'", ",", "aligned", "=", "True", ",", "return_names", "=", "True", ")", ":", "# Convert time to UTC", "start", "=", "self", ".", "convert_to_utc", "(", "start", ")", "end", "=", "self", ".", "convert_to_utc", "(", "end", ")", "request", "=", "self", ".", "compose_MDAL_dic", "(", "point_type", "=", "point_type", ",", "site", "=", "site", ",", "start", "=", "start", ",", "end", "=", "end", ",", "var", "=", "var", ",", "agg", "=", "agg", ",", "window", "=", "window", ",", "aligned", "=", "aligned", ")", "resp", "=", "self", ".", "m", ".", "query", "(", "request", ")", "if", "return_names", ":", "resp", "=", "self", ".", "replace_uuid_w_names", "(", "resp", ")", "return", "resp" ]
Get meter data from MDAL. Parameters ---------- site : str Building name. start : str Start date - 'YYYY-MM-DDTHH:MM:SSZ' end : str End date - 'YYYY-MM-DDTHH:MM:SSZ' point_type : str Type of data, i.e. Green_Button_Meter, Building_Electric_Meter... var : str Variable - "meter", "weather"... agg : str Aggregation - MEAN, SUM, RAW... window : str Size of the moving window. aligned : bool ??? return_names : bool ??? Returns ------- (df, mapping, context) ???
[ "Get", "meter", "data", "from", "MDAL", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Import_Data.py#L215-L258
2,080
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Import_Data.py
Import_MDAL.get_tstat
def get_tstat(self, site, start, end, var="tstat_temp", agg='MEAN', window='24h', aligned=True, return_names=True): """ Get thermostat data from MDAL. Parameters ---------- site : str Building name. start : str Start date - 'YYYY-MM-DDTHH:MM:SSZ' end : str End date - 'YYYY-MM-DDTHH:MM:SSZ' var : str Variable - "meter", "weather"... agg : str Aggregation - MEAN, SUM, RAW... window : str Size of the moving window. aligned : bool ??? return_names : bool ??? Returns ------- (df, mapping, context) ??? """ # Convert time to UTC start = self.convert_to_utc(start) end = self.convert_to_utc(end) point_map = { "tstat_state" : "Thermostat_Status", "tstat_hsp" : "Supply_Air_Temperature_Heating_Setpoint", "tstat_csp" : "Supply_Air_Temperature_Cooling_Setpoint", "tstat_temp": "Temperature_Sensor" } if isinstance(var,list): point_type = [point_map[point_type] for point_type in var] # list of all the point names using BRICK classes else: point_type = point_map[var] # single value using BRICK classes request = self.compose_MDAL_dic(point_type=point_type, site=site, start=start, end=end, var=var, agg=agg, window=window, aligned=aligned) resp = self.m.query(request) if return_names: resp = self.replace_uuid_w_names(resp) return resp
python
def get_tstat(self, site, start, end, var="tstat_temp", agg='MEAN', window='24h', aligned=True, return_names=True): """ Get thermostat data from MDAL. Parameters ---------- site : str Building name. start : str Start date - 'YYYY-MM-DDTHH:MM:SSZ' end : str End date - 'YYYY-MM-DDTHH:MM:SSZ' var : str Variable - "meter", "weather"... agg : str Aggregation - MEAN, SUM, RAW... window : str Size of the moving window. aligned : bool ??? return_names : bool ??? Returns ------- (df, mapping, context) ??? """ # Convert time to UTC start = self.convert_to_utc(start) end = self.convert_to_utc(end) point_map = { "tstat_state" : "Thermostat_Status", "tstat_hsp" : "Supply_Air_Temperature_Heating_Setpoint", "tstat_csp" : "Supply_Air_Temperature_Cooling_Setpoint", "tstat_temp": "Temperature_Sensor" } if isinstance(var,list): point_type = [point_map[point_type] for point_type in var] # list of all the point names using BRICK classes else: point_type = point_map[var] # single value using BRICK classes request = self.compose_MDAL_dic(point_type=point_type, site=site, start=start, end=end, var=var, agg=agg, window=window, aligned=aligned) resp = self.m.query(request) if return_names: resp = self.replace_uuid_w_names(resp) return resp
[ "def", "get_tstat", "(", "self", ",", "site", ",", "start", ",", "end", ",", "var", "=", "\"tstat_temp\"", ",", "agg", "=", "'MEAN'", ",", "window", "=", "'24h'", ",", "aligned", "=", "True", ",", "return_names", "=", "True", ")", ":", "# Convert time to UTC", "start", "=", "self", ".", "convert_to_utc", "(", "start", ")", "end", "=", "self", ".", "convert_to_utc", "(", "end", ")", "point_map", "=", "{", "\"tstat_state\"", ":", "\"Thermostat_Status\"", ",", "\"tstat_hsp\"", ":", "\"Supply_Air_Temperature_Heating_Setpoint\"", ",", "\"tstat_csp\"", ":", "\"Supply_Air_Temperature_Cooling_Setpoint\"", ",", "\"tstat_temp\"", ":", "\"Temperature_Sensor\"", "}", "if", "isinstance", "(", "var", ",", "list", ")", ":", "point_type", "=", "[", "point_map", "[", "point_type", "]", "for", "point_type", "in", "var", "]", "# list of all the point names using BRICK classes", "else", ":", "point_type", "=", "point_map", "[", "var", "]", "# single value using BRICK classes", "request", "=", "self", ".", "compose_MDAL_dic", "(", "point_type", "=", "point_type", ",", "site", "=", "site", ",", "start", "=", "start", ",", "end", "=", "end", ",", "var", "=", "var", ",", "agg", "=", "agg", ",", "window", "=", "window", ",", "aligned", "=", "aligned", ")", "resp", "=", "self", ".", "m", ".", "query", "(", "request", ")", "if", "return_names", ":", "resp", "=", "self", ".", "replace_uuid_w_names", "(", "resp", ")", "return", "resp" ]
Get thermostat data from MDAL. Parameters ---------- site : str Building name. start : str Start date - 'YYYY-MM-DDTHH:MM:SSZ' end : str End date - 'YYYY-MM-DDTHH:MM:SSZ' var : str Variable - "meter", "weather"... agg : str Aggregation - MEAN, SUM, RAW... window : str Size of the moving window. aligned : bool ??? return_names : bool ??? Returns ------- (df, mapping, context) ???
[ "Get", "thermostat", "data", "from", "MDAL", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Import_Data.py#L307-L359
2,081
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Import_Data.py
Import_MDAL.compose_MDAL_dic
def compose_MDAL_dic(self, site, point_type, start, end, var, agg, window, aligned, points=None, return_names=False): """ Create dictionary for MDAL request. Parameters ---------- site : str Building name. start : str Start date - 'YYYY-MM-DDTHH:MM:SSZ' end : str End date - 'YYYY-MM-DDTHH:MM:SSZ' point_type : str Type of data, i.e. Green_Button_Meter, Building_Electric_Meter... var : str Variable - "meter", "weather"... agg : str Aggregation - MEAN, SUM, RAW... window : str Size of the moving window. aligned : bool ??? return_names : bool ??? Returns ------- (df, mapping, context) ??? """ # Convert time to UTC start = self.convert_to_utc(start) end = self.convert_to_utc(end) request = {} # Add Time Details - single set for one or multiple series request['Time'] = { 'Start': start, 'End': end, 'Window': window, 'Aligned': aligned } # Define Variables request["Variables"] = {} request['Composition'] = [] request['Aggregation'] = {} if isinstance(point_type, str): # if point_type is a string -> single type of point requested request["Variables"][var] = self.compose_BRICK_query(point_type=point_type,site=site) # pass one point type at the time request['Composition'] = [var] request['Aggregation'][var] = [agg] elif isinstance(point_type, list): # loop through all the point_types and create one section of the brick query at the time for idx, point in enumerate(point_type): request["Variables"][var[idx]] = self.compose_BRICK_query(point_type=point,site=site) # pass one point type at the time request['Composition'].append(var[idx]) if isinstance(agg, str): # if agg is a string -> single type of aggregation requested request['Aggregation'][var[idx]] = [agg] elif isinstance(agg, list): # if agg is a list -> expected one agg per point request['Aggregation'][var[idx]] = [agg[idx]] return request
python
def compose_MDAL_dic(self, site, point_type, start, end, var, agg, window, aligned, points=None, return_names=False): """ Create dictionary for MDAL request. Parameters ---------- site : str Building name. start : str Start date - 'YYYY-MM-DDTHH:MM:SSZ' end : str End date - 'YYYY-MM-DDTHH:MM:SSZ' point_type : str Type of data, i.e. Green_Button_Meter, Building_Electric_Meter... var : str Variable - "meter", "weather"... agg : str Aggregation - MEAN, SUM, RAW... window : str Size of the moving window. aligned : bool ??? return_names : bool ??? Returns ------- (df, mapping, context) ??? """ # Convert time to UTC start = self.convert_to_utc(start) end = self.convert_to_utc(end) request = {} # Add Time Details - single set for one or multiple series request['Time'] = { 'Start': start, 'End': end, 'Window': window, 'Aligned': aligned } # Define Variables request["Variables"] = {} request['Composition'] = [] request['Aggregation'] = {} if isinstance(point_type, str): # if point_type is a string -> single type of point requested request["Variables"][var] = self.compose_BRICK_query(point_type=point_type,site=site) # pass one point type at the time request['Composition'] = [var] request['Aggregation'][var] = [agg] elif isinstance(point_type, list): # loop through all the point_types and create one section of the brick query at the time for idx, point in enumerate(point_type): request["Variables"][var[idx]] = self.compose_BRICK_query(point_type=point,site=site) # pass one point type at the time request['Composition'].append(var[idx]) if isinstance(agg, str): # if agg is a string -> single type of aggregation requested request['Aggregation'][var[idx]] = [agg] elif isinstance(agg, list): # if agg is a list -> expected one agg per point request['Aggregation'][var[idx]] = [agg[idx]] return request
[ "def", "compose_MDAL_dic", "(", "self", ",", "site", ",", "point_type", ",", "start", ",", "end", ",", "var", ",", "agg", ",", "window", ",", "aligned", ",", "points", "=", "None", ",", "return_names", "=", "False", ")", ":", "# Convert time to UTC", "start", "=", "self", ".", "convert_to_utc", "(", "start", ")", "end", "=", "self", ".", "convert_to_utc", "(", "end", ")", "request", "=", "{", "}", "# Add Time Details - single set for one or multiple series", "request", "[", "'Time'", "]", "=", "{", "'Start'", ":", "start", ",", "'End'", ":", "end", ",", "'Window'", ":", "window", ",", "'Aligned'", ":", "aligned", "}", "# Define Variables ", "request", "[", "\"Variables\"", "]", "=", "{", "}", "request", "[", "'Composition'", "]", "=", "[", "]", "request", "[", "'Aggregation'", "]", "=", "{", "}", "if", "isinstance", "(", "point_type", ",", "str", ")", ":", "# if point_type is a string -> single type of point requested", "request", "[", "\"Variables\"", "]", "[", "var", "]", "=", "self", ".", "compose_BRICK_query", "(", "point_type", "=", "point_type", ",", "site", "=", "site", ")", "# pass one point type at the time", "request", "[", "'Composition'", "]", "=", "[", "var", "]", "request", "[", "'Aggregation'", "]", "[", "var", "]", "=", "[", "agg", "]", "elif", "isinstance", "(", "point_type", ",", "list", ")", ":", "# loop through all the point_types and create one section of the brick query at the time", "for", "idx", ",", "point", "in", "enumerate", "(", "point_type", ")", ":", "request", "[", "\"Variables\"", "]", "[", "var", "[", "idx", "]", "]", "=", "self", ".", "compose_BRICK_query", "(", "point_type", "=", "point", ",", "site", "=", "site", ")", "# pass one point type at the time", "request", "[", "'Composition'", "]", ".", "append", "(", "var", "[", "idx", "]", ")", "if", "isinstance", "(", "agg", ",", "str", ")", ":", "# if agg is a string -> single type of aggregation requested", "request", "[", "'Aggregation'", "]", "[", "var", "[", "idx", "]", "]", "=", "[", "agg", "]", "elif", "isinstance", "(", "agg", ",", "list", ")", ":", "# if agg is a list -> expected one agg per point", "request", "[", "'Aggregation'", "]", "[", "var", "[", "idx", "]", "]", "=", "[", "agg", "[", "idx", "]", "]", "return", "request" ]
Create dictionary for MDAL request. Parameters ---------- site : str Building name. start : str Start date - 'YYYY-MM-DDTHH:MM:SSZ' end : str End date - 'YYYY-MM-DDTHH:MM:SSZ' point_type : str Type of data, i.e. Green_Button_Meter, Building_Electric_Meter... var : str Variable - "meter", "weather"... agg : str Aggregation - MEAN, SUM, RAW... window : str Size of the moving window. aligned : bool ??? return_names : bool ??? Returns ------- (df, mapping, context) ???
[ "Create", "dictionary", "for", "MDAL", "request", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Import_Data.py#L362-L428
2,082
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Import_Data.py
Import_MDAL.get_point_name
def get_point_name(self, context): """ Get point name. Parameters ---------- context : ??? ??? Returns ------- ??? ??? """ metadata_table = self.parse_context(context) return metadata_table.apply(self.strip_point_name, axis=1)
python
def get_point_name(self, context): """ Get point name. Parameters ---------- context : ??? ??? Returns ------- ??? ??? """ metadata_table = self.parse_context(context) return metadata_table.apply(self.strip_point_name, axis=1)
[ "def", "get_point_name", "(", "self", ",", "context", ")", ":", "metadata_table", "=", "self", ".", "parse_context", "(", "context", ")", "return", "metadata_table", ".", "apply", "(", "self", ".", "strip_point_name", ",", "axis", "=", "1", ")" ]
Get point name. Parameters ---------- context : ??? ??? Returns ------- ??? ???
[ "Get", "point", "name", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Import_Data.py#L510-L526
2,083
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Import_Data.py
Import_MDAL.replace_uuid_w_names
def replace_uuid_w_names(self, resp): """ Replace the uuid's with names. Parameters ---------- resp : ??? ??? Returns ------- ??? ??? """ col_mapper = self.get_point_name(resp.context)["?point"].to_dict() resp.df.rename(columns=col_mapper, inplace=True) return resp
python
def replace_uuid_w_names(self, resp): """ Replace the uuid's with names. Parameters ---------- resp : ??? ??? Returns ------- ??? ??? """ col_mapper = self.get_point_name(resp.context)["?point"].to_dict() resp.df.rename(columns=col_mapper, inplace=True) return resp
[ "def", "replace_uuid_w_names", "(", "self", ",", "resp", ")", ":", "col_mapper", "=", "self", ".", "get_point_name", "(", "resp", ".", "context", ")", "[", "\"?point\"", "]", ".", "to_dict", "(", ")", "resp", ".", "df", ".", "rename", "(", "columns", "=", "col_mapper", ",", "inplace", "=", "True", ")", "return", "resp" ]
Replace the uuid's with names. Parameters ---------- resp : ??? ??? Returns ------- ??? ???
[ "Replace", "the", "uuid", "s", "with", "names", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Import_Data.py#L529-L546
2,084
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Clean_Data.py
Clean_Data.resample_data
def resample_data(self, data, freq, resampler='mean'): """ Resample dataframe. Note ---- 1. Figure out how to apply different functions to different columns .apply() 2. This theoretically work in upsampling too, check docs http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html Parameters ---------- data : pd.DataFrame() Dataframe to resample freq : str Resampling frequency i.e. d, h, 15T... resampler : str Resampling type i.e. mean, max. Returns ------- pd.DataFrame() Dataframe containing resampled data """ if resampler == 'mean': data = data.resample(freq).mean() elif resampler == 'max': data = data.resample(freq).max() else: raise ValueError('Resampler can be \'mean\' or \'max\' only.') return data
python
def resample_data(self, data, freq, resampler='mean'): """ Resample dataframe. Note ---- 1. Figure out how to apply different functions to different columns .apply() 2. This theoretically work in upsampling too, check docs http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html Parameters ---------- data : pd.DataFrame() Dataframe to resample freq : str Resampling frequency i.e. d, h, 15T... resampler : str Resampling type i.e. mean, max. Returns ------- pd.DataFrame() Dataframe containing resampled data """ if resampler == 'mean': data = data.resample(freq).mean() elif resampler == 'max': data = data.resample(freq).max() else: raise ValueError('Resampler can be \'mean\' or \'max\' only.') return data
[ "def", "resample_data", "(", "self", ",", "data", ",", "freq", ",", "resampler", "=", "'mean'", ")", ":", "if", "resampler", "==", "'mean'", ":", "data", "=", "data", ".", "resample", "(", "freq", ")", ".", "mean", "(", ")", "elif", "resampler", "==", "'max'", ":", "data", "=", "data", ".", "resample", "(", "freq", ")", ".", "max", "(", ")", "else", ":", "raise", "ValueError", "(", "'Resampler can be \\'mean\\' or \\'max\\' only.'", ")", "return", "data" ]
Resample dataframe. Note ---- 1. Figure out how to apply different functions to different columns .apply() 2. This theoretically work in upsampling too, check docs http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html Parameters ---------- data : pd.DataFrame() Dataframe to resample freq : str Resampling frequency i.e. d, h, 15T... resampler : str Resampling type i.e. mean, max. Returns ------- pd.DataFrame() Dataframe containing resampled data
[ "Resample", "dataframe", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Clean_Data.py#L76-L108
2,085
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Clean_Data.py
Clean_Data.interpolate_data
def interpolate_data(self, data, limit, method): """ Interpolate dataframe. Parameters ---------- data : pd.DataFrame() Dataframe to interpolate limit : int Interpolation limit. method : str Interpolation method. Returns ------- pd.DataFrame() Dataframe containing interpolated data """ data = data.interpolate(how="index", limit=limit, method=method) return data
python
def interpolate_data(self, data, limit, method): """ Interpolate dataframe. Parameters ---------- data : pd.DataFrame() Dataframe to interpolate limit : int Interpolation limit. method : str Interpolation method. Returns ------- pd.DataFrame() Dataframe containing interpolated data """ data = data.interpolate(how="index", limit=limit, method=method) return data
[ "def", "interpolate_data", "(", "self", ",", "data", ",", "limit", ",", "method", ")", ":", "data", "=", "data", ".", "interpolate", "(", "how", "=", "\"index\"", ",", "limit", "=", "limit", ",", "method", "=", "method", ")", "return", "data" ]
Interpolate dataframe. Parameters ---------- data : pd.DataFrame() Dataframe to interpolate limit : int Interpolation limit. method : str Interpolation method. Returns ------- pd.DataFrame() Dataframe containing interpolated data
[ "Interpolate", "dataframe", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Clean_Data.py#L111-L130
2,086
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Clean_Data.py
Clean_Data.remove_na
def remove_na(self, data, remove_na_how): """ Remove NAs from dataframe. Parameters ---------- data : pd.DataFrame() Dataframe to remove NAs from. remove_na_how : str Specificies how to remove NA i.e. all, any... Returns ------- pd.DataFrame() Dataframe with NAs removed. """ data = data.dropna(how=remove_na_how) return data
python
def remove_na(self, data, remove_na_how): """ Remove NAs from dataframe. Parameters ---------- data : pd.DataFrame() Dataframe to remove NAs from. remove_na_how : str Specificies how to remove NA i.e. all, any... Returns ------- pd.DataFrame() Dataframe with NAs removed. """ data = data.dropna(how=remove_na_how) return data
[ "def", "remove_na", "(", "self", ",", "data", ",", "remove_na_how", ")", ":", "data", "=", "data", ".", "dropna", "(", "how", "=", "remove_na_how", ")", "return", "data" ]
Remove NAs from dataframe. Parameters ---------- data : pd.DataFrame() Dataframe to remove NAs from. remove_na_how : str Specificies how to remove NA i.e. all, any... Returns ------- pd.DataFrame() Dataframe with NAs removed.
[ "Remove", "NAs", "from", "dataframe", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Clean_Data.py#L133-L150
2,087
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Clean_Data.py
Clean_Data.remove_outlier
def remove_outlier(self, data, sd_val): """ Remove outliers from dataframe. Note ---- 1. This function excludes all lines with NA in all columns. Parameters ---------- data : pd.DataFrame() Dataframe to remove outliers from. sd_val : int Standard Deviation Value (specifices how many SDs away is a point considered an outlier) Returns ------- pd.DataFrame() Dataframe with outliers removed. """ data = data.dropna() data = data[(np.abs(stats.zscore(data)) < float(sd_val)).all(axis=1)] return data
python
def remove_outlier(self, data, sd_val): """ Remove outliers from dataframe. Note ---- 1. This function excludes all lines with NA in all columns. Parameters ---------- data : pd.DataFrame() Dataframe to remove outliers from. sd_val : int Standard Deviation Value (specifices how many SDs away is a point considered an outlier) Returns ------- pd.DataFrame() Dataframe with outliers removed. """ data = data.dropna() data = data[(np.abs(stats.zscore(data)) < float(sd_val)).all(axis=1)] return data
[ "def", "remove_outlier", "(", "self", ",", "data", ",", "sd_val", ")", ":", "data", "=", "data", ".", "dropna", "(", ")", "data", "=", "data", "[", "(", "np", ".", "abs", "(", "stats", ".", "zscore", "(", "data", ")", ")", "<", "float", "(", "sd_val", ")", ")", ".", "all", "(", "axis", "=", "1", ")", "]", "return", "data" ]
Remove outliers from dataframe. Note ---- 1. This function excludes all lines with NA in all columns. Parameters ---------- data : pd.DataFrame() Dataframe to remove outliers from. sd_val : int Standard Deviation Value (specifices how many SDs away is a point considered an outlier) Returns ------- pd.DataFrame() Dataframe with outliers removed.
[ "Remove", "outliers", "from", "dataframe", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Clean_Data.py#L153-L175
2,088
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Clean_Data.py
Clean_Data.remove_out_of_bounds
def remove_out_of_bounds(self, data, low_bound, high_bound): """ Remove out of bound datapoints from dataframe. This function removes all points < low_bound and > high_bound. To Do, 1. Add a different boundary for each column. Parameters ---------- data : pd.DataFrame() Dataframe to remove bounds from. low_bound : int Low bound of the data. high_bound : int High bound of the data. Returns ------- pd.DataFrame() Dataframe with out of bounds removed. """ data = data.dropna() data = data[(data > low_bound).all(axis=1) & (data < high_bound).all(axis=1)] return data
python
def remove_out_of_bounds(self, data, low_bound, high_bound): """ Remove out of bound datapoints from dataframe. This function removes all points < low_bound and > high_bound. To Do, 1. Add a different boundary for each column. Parameters ---------- data : pd.DataFrame() Dataframe to remove bounds from. low_bound : int Low bound of the data. high_bound : int High bound of the data. Returns ------- pd.DataFrame() Dataframe with out of bounds removed. """ data = data.dropna() data = data[(data > low_bound).all(axis=1) & (data < high_bound).all(axis=1)] return data
[ "def", "remove_out_of_bounds", "(", "self", ",", "data", ",", "low_bound", ",", "high_bound", ")", ":", "data", "=", "data", ".", "dropna", "(", ")", "data", "=", "data", "[", "(", "data", ">", "low_bound", ")", ".", "all", "(", "axis", "=", "1", ")", "&", "(", "data", "<", "high_bound", ")", ".", "all", "(", "axis", "=", "1", ")", "]", "return", "data" ]
Remove out of bound datapoints from dataframe. This function removes all points < low_bound and > high_bound. To Do, 1. Add a different boundary for each column. Parameters ---------- data : pd.DataFrame() Dataframe to remove bounds from. low_bound : int Low bound of the data. high_bound : int High bound of the data. Returns ------- pd.DataFrame() Dataframe with out of bounds removed.
[ "Remove", "out", "of", "bound", "datapoints", "from", "dataframe", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Clean_Data.py#L178-L203
2,089
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Clean_Data.py
Clean_Data._set_TS_index
def _set_TS_index(self, data): """ Convert index to datetime and all other columns to numeric Parameters ---------- data : pd.DataFrame() Input dataframe. Returns ------- pd.DataFrame() Modified dataframe. """ # Set index data.index = pd.to_datetime(data.index, error= "ignore") # Format types to numeric for col in data.columns: data[col] = pd.to_numeric(data[col], errors="coerce") return data
python
def _set_TS_index(self, data): """ Convert index to datetime and all other columns to numeric Parameters ---------- data : pd.DataFrame() Input dataframe. Returns ------- pd.DataFrame() Modified dataframe. """ # Set index data.index = pd.to_datetime(data.index, error= "ignore") # Format types to numeric for col in data.columns: data[col] = pd.to_numeric(data[col], errors="coerce") return data
[ "def", "_set_TS_index", "(", "self", ",", "data", ")", ":", "# Set index", "data", ".", "index", "=", "pd", ".", "to_datetime", "(", "data", ".", "index", ",", "error", "=", "\"ignore\"", ")", "# Format types to numeric", "for", "col", "in", "data", ".", "columns", ":", "data", "[", "col", "]", "=", "pd", ".", "to_numeric", "(", "data", "[", "col", "]", ",", "errors", "=", "\"coerce\"", ")", "return", "data" ]
Convert index to datetime and all other columns to numeric Parameters ---------- data : pd.DataFrame() Input dataframe. Returns ------- pd.DataFrame() Modified dataframe.
[ "Convert", "index", "to", "datetime", "and", "all", "other", "columns", "to", "numeric" ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Clean_Data.py#L283-L305
2,090
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Clean_Data.py
Clean_Data._utc_to_local
def _utc_to_local(self, data, local_zone="America/Los_Angeles"): """ Adjust index of dataframe according to timezone that is requested by user. Parameters ---------- data : pd.DataFrame() Pandas dataframe of json timeseries response from server. local_zone : str pytz.timezone string of specified local timezone to change index to. Returns ------- pd.DataFrame() Pandas dataframe with timestamp index adjusted for local timezone. """ # Accounts for localtime shift data.index = data.index.tz_localize(pytz.utc).tz_convert(local_zone) # Gets rid of extra offset information so can compare with csv data data.index = data.index.tz_localize(None) return data
python
def _utc_to_local(self, data, local_zone="America/Los_Angeles"): """ Adjust index of dataframe according to timezone that is requested by user. Parameters ---------- data : pd.DataFrame() Pandas dataframe of json timeseries response from server. local_zone : str pytz.timezone string of specified local timezone to change index to. Returns ------- pd.DataFrame() Pandas dataframe with timestamp index adjusted for local timezone. """ # Accounts for localtime shift data.index = data.index.tz_localize(pytz.utc).tz_convert(local_zone) # Gets rid of extra offset information so can compare with csv data data.index = data.index.tz_localize(None) return data
[ "def", "_utc_to_local", "(", "self", ",", "data", ",", "local_zone", "=", "\"America/Los_Angeles\"", ")", ":", "# Accounts for localtime shift", "data", ".", "index", "=", "data", ".", "index", ".", "tz_localize", "(", "pytz", ".", "utc", ")", ".", "tz_convert", "(", "local_zone", ")", "# Gets rid of extra offset information so can compare with csv data", "data", ".", "index", "=", "data", ".", "index", ".", "tz_localize", "(", "None", ")", "return", "data" ]
Adjust index of dataframe according to timezone that is requested by user. Parameters ---------- data : pd.DataFrame() Pandas dataframe of json timeseries response from server. local_zone : str pytz.timezone string of specified local timezone to change index to. Returns ------- pd.DataFrame() Pandas dataframe with timestamp index adjusted for local timezone.
[ "Adjust", "index", "of", "dataframe", "according", "to", "timezone", "that", "is", "requested", "by", "user", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Clean_Data.py#L308-L331
2,091
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Clean_Data.py
Clean_Data._local_to_utc
def _local_to_utc(self, timestamp, local_zone="America/Los_Angeles"): """ Convert local timestamp to UTC. Parameters ---------- timestamp : pd.DataFrame() Input Pandas dataframe whose index needs to be changed. local_zone : str Name of local zone. Defaults to PST. Returns ------- pd.DataFrame() Dataframe with UTC timestamps. """ timestamp_new = pd.to_datetime(timestamp, infer_datetime_format=True, errors='coerce') timestamp_new = timestamp_new.tz_localize(local_zone).tz_convert(pytz.utc) timestamp_new = timestamp_new.strftime('%Y-%m-%d %H:%M:%S') return timestamp_new
python
def _local_to_utc(self, timestamp, local_zone="America/Los_Angeles"): """ Convert local timestamp to UTC. Parameters ---------- timestamp : pd.DataFrame() Input Pandas dataframe whose index needs to be changed. local_zone : str Name of local zone. Defaults to PST. Returns ------- pd.DataFrame() Dataframe with UTC timestamps. """ timestamp_new = pd.to_datetime(timestamp, infer_datetime_format=True, errors='coerce') timestamp_new = timestamp_new.tz_localize(local_zone).tz_convert(pytz.utc) timestamp_new = timestamp_new.strftime('%Y-%m-%d %H:%M:%S') return timestamp_new
[ "def", "_local_to_utc", "(", "self", ",", "timestamp", ",", "local_zone", "=", "\"America/Los_Angeles\"", ")", ":", "timestamp_new", "=", "pd", ".", "to_datetime", "(", "timestamp", ",", "infer_datetime_format", "=", "True", ",", "errors", "=", "'coerce'", ")", "timestamp_new", "=", "timestamp_new", ".", "tz_localize", "(", "local_zone", ")", ".", "tz_convert", "(", "pytz", ".", "utc", ")", "timestamp_new", "=", "timestamp_new", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", "return", "timestamp_new" ]
Convert local timestamp to UTC. Parameters ---------- timestamp : pd.DataFrame() Input Pandas dataframe whose index needs to be changed. local_zone : str Name of local zone. Defaults to PST. Returns ------- pd.DataFrame() Dataframe with UTC timestamps.
[ "Convert", "local", "timestamp", "to", "UTC", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Clean_Data.py#L334-L354
2,092
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Clean_Data.py
Clean_Data.find_uuid
def find_uuid(self, obj, column_name): """ Find uuid. Parameters ---------- obj : ??? the object returned by the MDAL Query column_name : str input point returned from MDAL Query Returns ------- str the uuid that correlates with the data """ keys = obj.context.keys() for i in keys: if column_name in obj.context[i]['?point']: uuid = i return i
python
def find_uuid(self, obj, column_name): """ Find uuid. Parameters ---------- obj : ??? the object returned by the MDAL Query column_name : str input point returned from MDAL Query Returns ------- str the uuid that correlates with the data """ keys = obj.context.keys() for i in keys: if column_name in obj.context[i]['?point']: uuid = i return i
[ "def", "find_uuid", "(", "self", ",", "obj", ",", "column_name", ")", ":", "keys", "=", "obj", ".", "context", ".", "keys", "(", ")", "for", "i", "in", "keys", ":", "if", "column_name", "in", "obj", ".", "context", "[", "i", "]", "[", "'?point'", "]", ":", "uuid", "=", "i", "return", "i" ]
Find uuid. Parameters ---------- obj : ??? the object returned by the MDAL Query column_name : str input point returned from MDAL Query Returns ------- str the uuid that correlates with the data
[ "Find", "uuid", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Clean_Data.py#L952-L975
2,093
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Clean_Data.py
Clean_Data.identify_missing
def identify_missing(self, df, check_start=True): """ Identify missing data. Parameters ---------- df : pd.DataFrame() Dataframe to check for missing data. check_start : bool turns 0 to 1 for the first observation, to display the start of the data as the beginning of the missing data event Returns ------- pd.DataFrame(), str dataframe where 1 indicates missing data and 0 indicates reported data, returns the column name generated from the MDAL Query """ # Check start changes the first value of df to 1, when the data stream is initially missing # This allows the diff function to acknowledge the missing data data_missing = df.isnull() * 1 col_name = str(data_missing.columns[0]) # When there is no data stream at the beginning we change it to 1 if check_start & data_missing[col_name][0] == 1: data_missing[col_name][0] = 0 return data_missing, col_name
python
def identify_missing(self, df, check_start=True): """ Identify missing data. Parameters ---------- df : pd.DataFrame() Dataframe to check for missing data. check_start : bool turns 0 to 1 for the first observation, to display the start of the data as the beginning of the missing data event Returns ------- pd.DataFrame(), str dataframe where 1 indicates missing data and 0 indicates reported data, returns the column name generated from the MDAL Query """ # Check start changes the first value of df to 1, when the data stream is initially missing # This allows the diff function to acknowledge the missing data data_missing = df.isnull() * 1 col_name = str(data_missing.columns[0]) # When there is no data stream at the beginning we change it to 1 if check_start & data_missing[col_name][0] == 1: data_missing[col_name][0] = 0 return data_missing, col_name
[ "def", "identify_missing", "(", "self", ",", "df", ",", "check_start", "=", "True", ")", ":", "# Check start changes the first value of df to 1, when the data stream is initially missing", "# This allows the diff function to acknowledge the missing data", "data_missing", "=", "df", ".", "isnull", "(", ")", "*", "1", "col_name", "=", "str", "(", "data_missing", ".", "columns", "[", "0", "]", ")", "# When there is no data stream at the beginning we change it to 1", "if", "check_start", "&", "data_missing", "[", "col_name", "]", "[", "0", "]", "==", "1", ":", "data_missing", "[", "col_name", "]", "[", "0", "]", "=", "0", "return", "data_missing", ",", "col_name" ]
Identify missing data. Parameters ---------- df : pd.DataFrame() Dataframe to check for missing data. check_start : bool turns 0 to 1 for the first observation, to display the start of the data as the beginning of the missing data event Returns ------- pd.DataFrame(), str dataframe where 1 indicates missing data and 0 indicates reported data, returns the column name generated from the MDAL Query
[ "Identify", "missing", "data", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Clean_Data.py#L978-L1006
2,094
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Clean_Data.py
Clean_Data.diff_boolean
def diff_boolean(self, df, column_name=None, uuid=None, duration=True, min_event_filter='3 hours'): """ takes the dataframe of missing values, and returns a dataframe that indicates the length of each event where data was continuously missing Parameters ---------- df : pd.DataFrame() Dataframe to check for missing data (must be in boolean format where 1 indicates missing data. column_name : str the original column name produced by MDAL Query uuid : str the uuid associated with the meter, if known duration : bool If True, the duration will be displayed in the results. If false the column will be dropped. min_event_filter : str Filters out the events that are less than the given time period Returns ------- pd.DataFrame() dataframe with the start time of the event (as the index), end time of the event (first time when data is reported) """ if uuid == None: uuid = 'End' data_gaps = df[(df.diff() == 1) | (df.diff() == -1)].dropna() data_gaps["duration"] = abs(data_gaps.index.to_series().diff(periods=-1)) data_gaps[uuid] = data_gaps.index + (data_gaps["duration"]) data_gaps = data_gaps[data_gaps["duration"] > pd.Timedelta(min_event_filter)] data_gaps = data_gaps[data_gaps[column_name] == 1] data_gaps.pop(column_name) if not duration: data_gaps.pop('duration') data_gaps.index = data_gaps.index.strftime(date_format="%Y-%m-%d %H:%M:%S") data_gaps[uuid] = data_gaps[uuid].dt.strftime(date_format="%Y-%m-%d %H:%M:%S") return data_gaps
python
def diff_boolean(self, df, column_name=None, uuid=None, duration=True, min_event_filter='3 hours'): """ takes the dataframe of missing values, and returns a dataframe that indicates the length of each event where data was continuously missing Parameters ---------- df : pd.DataFrame() Dataframe to check for missing data (must be in boolean format where 1 indicates missing data. column_name : str the original column name produced by MDAL Query uuid : str the uuid associated with the meter, if known duration : bool If True, the duration will be displayed in the results. If false the column will be dropped. min_event_filter : str Filters out the events that are less than the given time period Returns ------- pd.DataFrame() dataframe with the start time of the event (as the index), end time of the event (first time when data is reported) """ if uuid == None: uuid = 'End' data_gaps = df[(df.diff() == 1) | (df.diff() == -1)].dropna() data_gaps["duration"] = abs(data_gaps.index.to_series().diff(periods=-1)) data_gaps[uuid] = data_gaps.index + (data_gaps["duration"]) data_gaps = data_gaps[data_gaps["duration"] > pd.Timedelta(min_event_filter)] data_gaps = data_gaps[data_gaps[column_name] == 1] data_gaps.pop(column_name) if not duration: data_gaps.pop('duration') data_gaps.index = data_gaps.index.strftime(date_format="%Y-%m-%d %H:%M:%S") data_gaps[uuid] = data_gaps[uuid].dt.strftime(date_format="%Y-%m-%d %H:%M:%S") return data_gaps
[ "def", "diff_boolean", "(", "self", ",", "df", ",", "column_name", "=", "None", ",", "uuid", "=", "None", ",", "duration", "=", "True", ",", "min_event_filter", "=", "'3 hours'", ")", ":", "if", "uuid", "==", "None", ":", "uuid", "=", "'End'", "data_gaps", "=", "df", "[", "(", "df", ".", "diff", "(", ")", "==", "1", ")", "|", "(", "df", ".", "diff", "(", ")", "==", "-", "1", ")", "]", ".", "dropna", "(", ")", "data_gaps", "[", "\"duration\"", "]", "=", "abs", "(", "data_gaps", ".", "index", ".", "to_series", "(", ")", ".", "diff", "(", "periods", "=", "-", "1", ")", ")", "data_gaps", "[", "uuid", "]", "=", "data_gaps", ".", "index", "+", "(", "data_gaps", "[", "\"duration\"", "]", ")", "data_gaps", "=", "data_gaps", "[", "data_gaps", "[", "\"duration\"", "]", ">", "pd", ".", "Timedelta", "(", "min_event_filter", ")", "]", "data_gaps", "=", "data_gaps", "[", "data_gaps", "[", "column_name", "]", "==", "1", "]", "data_gaps", ".", "pop", "(", "column_name", ")", "if", "not", "duration", ":", "data_gaps", ".", "pop", "(", "'duration'", ")", "data_gaps", ".", "index", "=", "data_gaps", ".", "index", ".", "strftime", "(", "date_format", "=", "\"%Y-%m-%d %H:%M:%S\"", ")", "data_gaps", "[", "uuid", "]", "=", "data_gaps", "[", "uuid", "]", ".", "dt", ".", "strftime", "(", "date_format", "=", "\"%Y-%m-%d %H:%M:%S\"", ")", "return", "data_gaps" ]
takes the dataframe of missing values, and returns a dataframe that indicates the length of each event where data was continuously missing Parameters ---------- df : pd.DataFrame() Dataframe to check for missing data (must be in boolean format where 1 indicates missing data. column_name : str the original column name produced by MDAL Query uuid : str the uuid associated with the meter, if known duration : bool If True, the duration will be displayed in the results. If false the column will be dropped. min_event_filter : str Filters out the events that are less than the given time period Returns ------- pd.DataFrame() dataframe with the start time of the event (as the index), end time of the event (first time when data is reported)
[ "takes", "the", "dataframe", "of", "missing", "values", "and", "returns", "a", "dataframe", "that", "indicates", "the", "length", "of", "each", "event", "where", "data", "was", "continuously", "missing" ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Clean_Data.py#L1009-L1050
2,095
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Clean_Data.py
Clean_Data.analyze_quality_table
def analyze_quality_table(self, obj,low_bound=None, high_bound=None): """ Takes in an the object returned by the MDAL query, and analyzes the quality of the data for each column in the df. Returns a df of data quality metrics To Do ----- Need to make it specific for varying meters and label it for each type, Either separate functions or make the function broader Parameters ---------- obj : ??? the object returned by the MDAL Query low_bound : float all data equal to or below this value will be interpreted as missing data high_bound : float all data above this value will be interpreted as missing Returns ------- pd.DataFrame() returns data frame with % missing data, average duration of missing data event and standard deviation of that duration for each column of data """ data = obj.df N_rows = 3 N_cols = data.shape[1] d = pd.DataFrame(np.zeros((N_rows, N_cols)), index=['% Missing', 'AVG Length Missing', 'Std dev. Missing'], columns=[data.columns]) if low_bound: data = data.where(data >= low_bound) if high_bound: data=data.where(data < high_bound) for i in range(N_cols): data_per_meter = data.iloc[:, [i]] data_missing, meter = self.identify_missing(data_per_meter) percentage = data_missing.sum() / (data.shape[0]) * 100 data_gaps = self.diff_boolean(data_missing, column_name=meter) missing_mean = data_gaps.mean() std_dev = data_gaps.std() d.loc["% Missing", meter] = percentage[meter] d.loc["AVG Length Missing", meter] = missing_mean['duration'] d.loc["Std dev. Missing", meter] = std_dev['duration'] return d
python
def analyze_quality_table(self, obj,low_bound=None, high_bound=None): """ Takes in an the object returned by the MDAL query, and analyzes the quality of the data for each column in the df. Returns a df of data quality metrics To Do ----- Need to make it specific for varying meters and label it for each type, Either separate functions or make the function broader Parameters ---------- obj : ??? the object returned by the MDAL Query low_bound : float all data equal to or below this value will be interpreted as missing data high_bound : float all data above this value will be interpreted as missing Returns ------- pd.DataFrame() returns data frame with % missing data, average duration of missing data event and standard deviation of that duration for each column of data """ data = obj.df N_rows = 3 N_cols = data.shape[1] d = pd.DataFrame(np.zeros((N_rows, N_cols)), index=['% Missing', 'AVG Length Missing', 'Std dev. Missing'], columns=[data.columns]) if low_bound: data = data.where(data >= low_bound) if high_bound: data=data.where(data < high_bound) for i in range(N_cols): data_per_meter = data.iloc[:, [i]] data_missing, meter = self.identify_missing(data_per_meter) percentage = data_missing.sum() / (data.shape[0]) * 100 data_gaps = self.diff_boolean(data_missing, column_name=meter) missing_mean = data_gaps.mean() std_dev = data_gaps.std() d.loc["% Missing", meter] = percentage[meter] d.loc["AVG Length Missing", meter] = missing_mean['duration'] d.loc["Std dev. Missing", meter] = std_dev['duration'] return d
[ "def", "analyze_quality_table", "(", "self", ",", "obj", ",", "low_bound", "=", "None", ",", "high_bound", "=", "None", ")", ":", "data", "=", "obj", ".", "df", "N_rows", "=", "3", "N_cols", "=", "data", ".", "shape", "[", "1", "]", "d", "=", "pd", ".", "DataFrame", "(", "np", ".", "zeros", "(", "(", "N_rows", ",", "N_cols", ")", ")", ",", "index", "=", "[", "'% Missing'", ",", "'AVG Length Missing'", ",", "'Std dev. Missing'", "]", ",", "columns", "=", "[", "data", ".", "columns", "]", ")", "if", "low_bound", ":", "data", "=", "data", ".", "where", "(", "data", ">=", "low_bound", ")", "if", "high_bound", ":", "data", "=", "data", ".", "where", "(", "data", "<", "high_bound", ")", "for", "i", "in", "range", "(", "N_cols", ")", ":", "data_per_meter", "=", "data", ".", "iloc", "[", ":", ",", "[", "i", "]", "]", "data_missing", ",", "meter", "=", "self", ".", "identify_missing", "(", "data_per_meter", ")", "percentage", "=", "data_missing", ".", "sum", "(", ")", "/", "(", "data", ".", "shape", "[", "0", "]", ")", "*", "100", "data_gaps", "=", "self", ".", "diff_boolean", "(", "data_missing", ",", "column_name", "=", "meter", ")", "missing_mean", "=", "data_gaps", ".", "mean", "(", ")", "std_dev", "=", "data_gaps", ".", "std", "(", ")", "d", ".", "loc", "[", "\"% Missing\"", ",", "meter", "]", "=", "percentage", "[", "meter", "]", "d", ".", "loc", "[", "\"AVG Length Missing\"", ",", "meter", "]", "=", "missing_mean", "[", "'duration'", "]", "d", ".", "loc", "[", "\"Std dev. Missing\"", ",", "meter", "]", "=", "std_dev", "[", "'duration'", "]", "return", "d" ]
Takes in an the object returned by the MDAL query, and analyzes the quality of the data for each column in the df. Returns a df of data quality metrics To Do ----- Need to make it specific for varying meters and label it for each type, Either separate functions or make the function broader Parameters ---------- obj : ??? the object returned by the MDAL Query low_bound : float all data equal to or below this value will be interpreted as missing data high_bound : float all data above this value will be interpreted as missing Returns ------- pd.DataFrame() returns data frame with % missing data, average duration of missing data event and standard deviation of that duration for each column of data
[ "Takes", "in", "an", "the", "object", "returned", "by", "the", "MDAL", "query", "and", "analyzes", "the", "quality", "of", "the", "data", "for", "each", "column", "in", "the", "df", ".", "Returns", "a", "df", "of", "data", "quality", "metrics" ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Clean_Data.py#L1053-L1108
2,096
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Clean_Data.py
Clean_Data.analyze_quality_graph
def analyze_quality_graph(self, obj): """ Takes in an the object returned by the MDAL query, and analyzes the quality of the data for each column in the df in the form of graphs. The Graphs returned show missing data events over time, and missing data frequency during each hour of the day To Do ----- Need to make it specific for varying meters and label it for each type, Either separate functions or make the function broader Parameters ---------- obj : ??? the object returned by the MDAL Query """ data = obj.df for i in range(data.shape[1]): data_per_meter = data.iloc[:, [i]] # need to make this work or change the structure data_missing, meter = self.identify_missing(data_per_meter) percentage = data_missing.sum() / (data.shape[0]) * 100 print('Percentage Missing of ' + meter + ' data: ' + str(int(percentage)) + '%') data_missing.plot(figsize=(18, 5), x_compat=True, title=meter + " Missing Data over the Time interval") data_gaps = self.diff_boolean(data_missing, column_name=meter) data_missing['Hour'] = data_missing.index.hour ymax = int(data_missing.groupby('Hour').sum().max() + 10) data_missing.groupby('Hour').sum().plot(ylim=(0, ymax), figsize=(18, 5), title=meter + " Time of Day of Missing Data") print(data_gaps)
python
def analyze_quality_graph(self, obj): """ Takes in an the object returned by the MDAL query, and analyzes the quality of the data for each column in the df in the form of graphs. The Graphs returned show missing data events over time, and missing data frequency during each hour of the day To Do ----- Need to make it specific for varying meters and label it for each type, Either separate functions or make the function broader Parameters ---------- obj : ??? the object returned by the MDAL Query """ data = obj.df for i in range(data.shape[1]): data_per_meter = data.iloc[:, [i]] # need to make this work or change the structure data_missing, meter = self.identify_missing(data_per_meter) percentage = data_missing.sum() / (data.shape[0]) * 100 print('Percentage Missing of ' + meter + ' data: ' + str(int(percentage)) + '%') data_missing.plot(figsize=(18, 5), x_compat=True, title=meter + " Missing Data over the Time interval") data_gaps = self.diff_boolean(data_missing, column_name=meter) data_missing['Hour'] = data_missing.index.hour ymax = int(data_missing.groupby('Hour').sum().max() + 10) data_missing.groupby('Hour').sum().plot(ylim=(0, ymax), figsize=(18, 5), title=meter + " Time of Day of Missing Data") print(data_gaps)
[ "def", "analyze_quality_graph", "(", "self", ",", "obj", ")", ":", "data", "=", "obj", ".", "df", "for", "i", "in", "range", "(", "data", ".", "shape", "[", "1", "]", ")", ":", "data_per_meter", "=", "data", ".", "iloc", "[", ":", ",", "[", "i", "]", "]", "# need to make this work or change the structure", "data_missing", ",", "meter", "=", "self", ".", "identify_missing", "(", "data_per_meter", ")", "percentage", "=", "data_missing", ".", "sum", "(", ")", "/", "(", "data", ".", "shape", "[", "0", "]", ")", "*", "100", "print", "(", "'Percentage Missing of '", "+", "meter", "+", "' data: '", "+", "str", "(", "int", "(", "percentage", ")", ")", "+", "'%'", ")", "data_missing", ".", "plot", "(", "figsize", "=", "(", "18", ",", "5", ")", ",", "x_compat", "=", "True", ",", "title", "=", "meter", "+", "\" Missing Data over the Time interval\"", ")", "data_gaps", "=", "self", ".", "diff_boolean", "(", "data_missing", ",", "column_name", "=", "meter", ")", "data_missing", "[", "'Hour'", "]", "=", "data_missing", ".", "index", ".", "hour", "ymax", "=", "int", "(", "data_missing", ".", "groupby", "(", "'Hour'", ")", ".", "sum", "(", ")", ".", "max", "(", ")", "+", "10", ")", "data_missing", ".", "groupby", "(", "'Hour'", ")", ".", "sum", "(", ")", ".", "plot", "(", "ylim", "=", "(", "0", ",", "ymax", ")", ",", "figsize", "=", "(", "18", ",", "5", ")", ",", "title", "=", "meter", "+", "\" Time of Day of Missing Data\"", ")", "print", "(", "data_gaps", ")" ]
Takes in an the object returned by the MDAL query, and analyzes the quality of the data for each column in the df in the form of graphs. The Graphs returned show missing data events over time, and missing data frequency during each hour of the day To Do ----- Need to make it specific for varying meters and label it for each type, Either separate functions or make the function broader Parameters ---------- obj : ??? the object returned by the MDAL Query
[ "Takes", "in", "an", "the", "object", "returned", "by", "the", "MDAL", "query", "and", "analyzes", "the", "quality", "of", "the", "data", "for", "each", "column", "in", "the", "df", "in", "the", "form", "of", "graphs", ".", "The", "Graphs", "returned", "show", "missing", "data", "events", "over", "time", "and", "missing", "data", "frequency", "during", "each", "hour", "of", "the", "day" ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Clean_Data.py#L1111-L1147
2,097
SoftwareDefinedBuildings/XBOS
apps/data_analysis/XBOS_data_analytics/Clean_Data.py
Clean_Data.clean_data
def clean_data(self, resample=True, freq='h', resampler='mean', interpolate=True, limit=1, method='linear', remove_na=True, remove_na_how='any', remove_outliers=True, sd_val=3, remove_out_of_bounds=True, low_bound=0, high_bound=9998): """ Clean dataframe. Parameters ---------- resample : bool Indicates whether to resample data or not. freq : str Resampling frequency i.e. d, h, 15T... resampler : str Resampling type i.e. mean, max. interpolate : bool Indicates whether to interpolate data or not. limit : int Interpolation limit. method : str Interpolation method. remove_na : bool Indicates whether to remove NAs or not. remove_na_how : str Specificies how to remove NA i.e. all, any... remove_outliers : bool Indicates whether to remove outliers or not. sd_val : int Standard Deviation Value (specifices how many SDs away is a point considered an outlier) remove_out_of_bounds : bool Indicates whether to remove out of bounds datapoints or not. low_bound : int Low bound of the data. high_bound : int High bound of the data. """ # Store copy of the original data data = self.original_data if resample: try: data = self.resample_data(data, freq, resampler) except Exception as e: raise e if interpolate: try: data = self.interpolate_data(data, limit=limit, method=method) except Exception as e: raise e if remove_na: try: data = self.remove_na(data, remove_na_how) except Exception as e: raise e if remove_outliers: try: data = self.remove_outliers(data, sd_val) except Exception as e: raise e if remove_out_of_bounds: try: data = self.remove_out_of_bounds(data, low_bound, high_bound) except Exception as e: raise e self.cleaned_data = data
python
def clean_data(self, resample=True, freq='h', resampler='mean', interpolate=True, limit=1, method='linear', remove_na=True, remove_na_how='any', remove_outliers=True, sd_val=3, remove_out_of_bounds=True, low_bound=0, high_bound=9998): """ Clean dataframe. Parameters ---------- resample : bool Indicates whether to resample data or not. freq : str Resampling frequency i.e. d, h, 15T... resampler : str Resampling type i.e. mean, max. interpolate : bool Indicates whether to interpolate data or not. limit : int Interpolation limit. method : str Interpolation method. remove_na : bool Indicates whether to remove NAs or not. remove_na_how : str Specificies how to remove NA i.e. all, any... remove_outliers : bool Indicates whether to remove outliers or not. sd_val : int Standard Deviation Value (specifices how many SDs away is a point considered an outlier) remove_out_of_bounds : bool Indicates whether to remove out of bounds datapoints or not. low_bound : int Low bound of the data. high_bound : int High bound of the data. """ # Store copy of the original data data = self.original_data if resample: try: data = self.resample_data(data, freq, resampler) except Exception as e: raise e if interpolate: try: data = self.interpolate_data(data, limit=limit, method=method) except Exception as e: raise e if remove_na: try: data = self.remove_na(data, remove_na_how) except Exception as e: raise e if remove_outliers: try: data = self.remove_outliers(data, sd_val) except Exception as e: raise e if remove_out_of_bounds: try: data = self.remove_out_of_bounds(data, low_bound, high_bound) except Exception as e: raise e self.cleaned_data = data
[ "def", "clean_data", "(", "self", ",", "resample", "=", "True", ",", "freq", "=", "'h'", ",", "resampler", "=", "'mean'", ",", "interpolate", "=", "True", ",", "limit", "=", "1", ",", "method", "=", "'linear'", ",", "remove_na", "=", "True", ",", "remove_na_how", "=", "'any'", ",", "remove_outliers", "=", "True", ",", "sd_val", "=", "3", ",", "remove_out_of_bounds", "=", "True", ",", "low_bound", "=", "0", ",", "high_bound", "=", "9998", ")", ":", "# Store copy of the original data", "data", "=", "self", ".", "original_data", "if", "resample", ":", "try", ":", "data", "=", "self", ".", "resample_data", "(", "data", ",", "freq", ",", "resampler", ")", "except", "Exception", "as", "e", ":", "raise", "e", "if", "interpolate", ":", "try", ":", "data", "=", "self", ".", "interpolate_data", "(", "data", ",", "limit", "=", "limit", ",", "method", "=", "method", ")", "except", "Exception", "as", "e", ":", "raise", "e", "if", "remove_na", ":", "try", ":", "data", "=", "self", ".", "remove_na", "(", "data", ",", "remove_na_how", ")", "except", "Exception", "as", "e", ":", "raise", "e", "if", "remove_outliers", ":", "try", ":", "data", "=", "self", ".", "remove_outliers", "(", "data", ",", "sd_val", ")", "except", "Exception", "as", "e", ":", "raise", "e", "if", "remove_out_of_bounds", ":", "try", ":", "data", "=", "self", ".", "remove_out_of_bounds", "(", "data", ",", "low_bound", ",", "high_bound", ")", "except", "Exception", "as", "e", ":", "raise", "e", "self", ".", "cleaned_data", "=", "data" ]
Clean dataframe. Parameters ---------- resample : bool Indicates whether to resample data or not. freq : str Resampling frequency i.e. d, h, 15T... resampler : str Resampling type i.e. mean, max. interpolate : bool Indicates whether to interpolate data or not. limit : int Interpolation limit. method : str Interpolation method. remove_na : bool Indicates whether to remove NAs or not. remove_na_how : str Specificies how to remove NA i.e. all, any... remove_outliers : bool Indicates whether to remove outliers or not. sd_val : int Standard Deviation Value (specifices how many SDs away is a point considered an outlier) remove_out_of_bounds : bool Indicates whether to remove out of bounds datapoints or not. low_bound : int Low bound of the data. high_bound : int High bound of the data.
[ "Clean", "dataframe", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/data_analysis/XBOS_data_analytics/Clean_Data.py#L198-L269
2,098
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Wrapper.py
Wrapper.write_json
def write_json(self): """ Dump data into json file. """ with open(self.results_folder_name + '/results-' + str(self.get_global_count()) + '.json', 'a') as f: json.dump(self.result, f)
python
def write_json(self): """ Dump data into json file. """ with open(self.results_folder_name + '/results-' + str(self.get_global_count()) + '.json', 'a') as f: json.dump(self.result, f)
[ "def", "write_json", "(", "self", ")", ":", "with", "open", "(", "self", ".", "results_folder_name", "+", "'/results-'", "+", "str", "(", "self", ".", "get_global_count", "(", ")", ")", "+", "'.json'", ",", "'a'", ")", "as", "f", ":", "json", ".", "dump", "(", "self", ".", "result", ",", "f", ")" ]
Dump data into json file.
[ "Dump", "data", "into", "json", "file", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Wrapper.py#L143-L147
2,099
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Wrapper.py
Wrapper.site_analysis
def site_analysis(self, folder_name, site_install_mapping, end_date): """ Summarize site data into a single table. folder_name : str Folder where all site data resides. site_event_mapping : dic Dictionary of site name to date of installation. end_date : str End date of data collected. """ def count_number_of_days(site, end_date): """ Counts the number of days between two dates. Parameters ---------- site : str Key to a dic containing site_name -> pelican installation date. end_date : str End date. Returns ------- int Number of days """ start_date = site_install_mapping[site] start_date = start_date.split('-') start = date(int(start_date[0]), int(start_date[1]), int(start_date[2])) end_date = end_date.split('-') end = date(int(end_date[0]), int(end_date[1]), int(end_date[2])) delta = end - start return delta.days if not folder_name or not isinstance(folder_name, str): raise TypeError("folder_name should be type string") else: list_json_files = [] df = pd.DataFrame() temp_df = pd.DataFrame() json_files = [f for f in os.listdir(folder_name) if f.endswith('.json')] for json_file in json_files: with open(folder_name + json_file) as f: js = json.load(f) num_days = count_number_of_days(js['Site'], end_date) e_abs_sav = round(js['Energy Savings (absolute)'] / 1000, 2) # Energy Absolute Savings e_perc_sav = round(js['Energy Savings (%)'], 2) # Energy Percent Savings ann_e_abs_sav = (e_abs_sav / num_days) * 365 # Annualized Energy Absolute Savings d_abs_sav = round(js['User Comments']['Dollar Savings (absolute)'], 2) # Dollar Absolute Savings d_perc_sav = round(js['User Comments']['Dollar Savings (%)'], 2) # Dollar Percent Savings ann_d_abs_sav = (d_abs_sav / num_days) * 365 # Annualized Dollar Absolute Savings temp_df = pd.DataFrame({ 'Site': js['Site'], '#Days since Pelican Installation': num_days, 'Energy Savings (%)': e_perc_sav, 'Energy Savings (kWh)': e_abs_sav, 'Annualized Energy Savings (kWh)': ann_e_abs_sav, 'Dollar Savings (%)': d_perc_sav, 'Dollar Savings ($)': d_abs_sav, 'Annualized Dollar Savings ($)': ann_d_abs_sav, 'Best Model': js['Model']['Optimal Model\'s Metrics']['name'], 'Adj R2': round(js['Model']['Optimal Model\'s Metrics']['adj_cross_val_score'], 2), 'RMSE': round(js['Model']['Optimal Model\'s Metrics']['rmse'], 2), 'MAPE': js['Model']['Optimal Model\'s Metrics']['mape'], 'Uncertainity': js['Uncertainity'], }, index=[0]) df = df.append(temp_df) df.set_index('Site', inplace=True) return df
python
def site_analysis(self, folder_name, site_install_mapping, end_date): """ Summarize site data into a single table. folder_name : str Folder where all site data resides. site_event_mapping : dic Dictionary of site name to date of installation. end_date : str End date of data collected. """ def count_number_of_days(site, end_date): """ Counts the number of days between two dates. Parameters ---------- site : str Key to a dic containing site_name -> pelican installation date. end_date : str End date. Returns ------- int Number of days """ start_date = site_install_mapping[site] start_date = start_date.split('-') start = date(int(start_date[0]), int(start_date[1]), int(start_date[2])) end_date = end_date.split('-') end = date(int(end_date[0]), int(end_date[1]), int(end_date[2])) delta = end - start return delta.days if not folder_name or not isinstance(folder_name, str): raise TypeError("folder_name should be type string") else: list_json_files = [] df = pd.DataFrame() temp_df = pd.DataFrame() json_files = [f for f in os.listdir(folder_name) if f.endswith('.json')] for json_file in json_files: with open(folder_name + json_file) as f: js = json.load(f) num_days = count_number_of_days(js['Site'], end_date) e_abs_sav = round(js['Energy Savings (absolute)'] / 1000, 2) # Energy Absolute Savings e_perc_sav = round(js['Energy Savings (%)'], 2) # Energy Percent Savings ann_e_abs_sav = (e_abs_sav / num_days) * 365 # Annualized Energy Absolute Savings d_abs_sav = round(js['User Comments']['Dollar Savings (absolute)'], 2) # Dollar Absolute Savings d_perc_sav = round(js['User Comments']['Dollar Savings (%)'], 2) # Dollar Percent Savings ann_d_abs_sav = (d_abs_sav / num_days) * 365 # Annualized Dollar Absolute Savings temp_df = pd.DataFrame({ 'Site': js['Site'], '#Days since Pelican Installation': num_days, 'Energy Savings (%)': e_perc_sav, 'Energy Savings (kWh)': e_abs_sav, 'Annualized Energy Savings (kWh)': ann_e_abs_sav, 'Dollar Savings (%)': d_perc_sav, 'Dollar Savings ($)': d_abs_sav, 'Annualized Dollar Savings ($)': ann_d_abs_sav, 'Best Model': js['Model']['Optimal Model\'s Metrics']['name'], 'Adj R2': round(js['Model']['Optimal Model\'s Metrics']['adj_cross_val_score'], 2), 'RMSE': round(js['Model']['Optimal Model\'s Metrics']['rmse'], 2), 'MAPE': js['Model']['Optimal Model\'s Metrics']['mape'], 'Uncertainity': js['Uncertainity'], }, index=[0]) df = df.append(temp_df) df.set_index('Site', inplace=True) return df
[ "def", "site_analysis", "(", "self", ",", "folder_name", ",", "site_install_mapping", ",", "end_date", ")", ":", "def", "count_number_of_days", "(", "site", ",", "end_date", ")", ":", "\"\"\" Counts the number of days between two dates.\n\n Parameters\n ----------\n site : str\n Key to a dic containing site_name -> pelican installation date.\n end_date : str\n End date.\n\n Returns\n -------\n int\n Number of days\n\n \"\"\"", "start_date", "=", "site_install_mapping", "[", "site", "]", "start_date", "=", "start_date", ".", "split", "(", "'-'", ")", "start", "=", "date", "(", "int", "(", "start_date", "[", "0", "]", ")", ",", "int", "(", "start_date", "[", "1", "]", ")", ",", "int", "(", "start_date", "[", "2", "]", ")", ")", "end_date", "=", "end_date", ".", "split", "(", "'-'", ")", "end", "=", "date", "(", "int", "(", "end_date", "[", "0", "]", ")", ",", "int", "(", "end_date", "[", "1", "]", ")", ",", "int", "(", "end_date", "[", "2", "]", ")", ")", "delta", "=", "end", "-", "start", "return", "delta", ".", "days", "if", "not", "folder_name", "or", "not", "isinstance", "(", "folder_name", ",", "str", ")", ":", "raise", "TypeError", "(", "\"folder_name should be type string\"", ")", "else", ":", "list_json_files", "=", "[", "]", "df", "=", "pd", ".", "DataFrame", "(", ")", "temp_df", "=", "pd", ".", "DataFrame", "(", ")", "json_files", "=", "[", "f", "for", "f", "in", "os", ".", "listdir", "(", "folder_name", ")", "if", "f", ".", "endswith", "(", "'.json'", ")", "]", "for", "json_file", "in", "json_files", ":", "with", "open", "(", "folder_name", "+", "json_file", ")", "as", "f", ":", "js", "=", "json", ".", "load", "(", "f", ")", "num_days", "=", "count_number_of_days", "(", "js", "[", "'Site'", "]", ",", "end_date", ")", "e_abs_sav", "=", "round", "(", "js", "[", "'Energy Savings (absolute)'", "]", "/", "1000", ",", "2", ")", "# Energy Absolute Savings", "e_perc_sav", "=", "round", "(", "js", "[", "'Energy Savings (%)'", "]", ",", "2", ")", "# Energy Percent Savings", "ann_e_abs_sav", "=", "(", "e_abs_sav", "/", "num_days", ")", "*", "365", "# Annualized Energy Absolute Savings", "d_abs_sav", "=", "round", "(", "js", "[", "'User Comments'", "]", "[", "'Dollar Savings (absolute)'", "]", ",", "2", ")", "# Dollar Absolute Savings", "d_perc_sav", "=", "round", "(", "js", "[", "'User Comments'", "]", "[", "'Dollar Savings (%)'", "]", ",", "2", ")", "# Dollar Percent Savings", "ann_d_abs_sav", "=", "(", "d_abs_sav", "/", "num_days", ")", "*", "365", "# Annualized Dollar Absolute Savings", "temp_df", "=", "pd", ".", "DataFrame", "(", "{", "'Site'", ":", "js", "[", "'Site'", "]", ",", "'#Days since Pelican Installation'", ":", "num_days", ",", "'Energy Savings (%)'", ":", "e_perc_sav", ",", "'Energy Savings (kWh)'", ":", "e_abs_sav", ",", "'Annualized Energy Savings (kWh)'", ":", "ann_e_abs_sav", ",", "'Dollar Savings (%)'", ":", "d_perc_sav", ",", "'Dollar Savings ($)'", ":", "d_abs_sav", ",", "'Annualized Dollar Savings ($)'", ":", "ann_d_abs_sav", ",", "'Best Model'", ":", "js", "[", "'Model'", "]", "[", "'Optimal Model\\'s Metrics'", "]", "[", "'name'", "]", ",", "'Adj R2'", ":", "round", "(", "js", "[", "'Model'", "]", "[", "'Optimal Model\\'s Metrics'", "]", "[", "'adj_cross_val_score'", "]", ",", "2", ")", ",", "'RMSE'", ":", "round", "(", "js", "[", "'Model'", "]", "[", "'Optimal Model\\'s Metrics'", "]", "[", "'rmse'", "]", ",", "2", ")", ",", "'MAPE'", ":", "js", "[", "'Model'", "]", "[", "'Optimal Model\\'s Metrics'", "]", "[", "'mape'", "]", ",", "'Uncertainity'", ":", "js", "[", "'Uncertainity'", "]", ",", "}", ",", "index", "=", "[", "0", "]", ")", "df", "=", "df", ".", "append", "(", "temp_df", ")", "df", ".", "set_index", "(", "'Site'", ",", "inplace", "=", "True", ")", "return", "df" ]
Summarize site data into a single table. folder_name : str Folder where all site data resides. site_event_mapping : dic Dictionary of site name to date of installation. end_date : str End date of data collected.
[ "Summarize", "site", "data", "into", "a", "single", "table", "." ]
c12d4fb14518ea3ae98c471c28e0710fdf74dd25
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Wrapper.py#L150-L235