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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
fhs/pyhdf | pyhdf/VS.py | VS.storedata | def storedata(self, fieldName, values, data_type, vName, vClass):
"""Create and initialize a single field vdata, returning
the vdata reference number.
Args::
fieldName Name of the single field in the vadata to create
values Sequence of values to store in the field;. Each value can
itself be a sequence, in which case the field will be
multivalued (all second-level sequences must be of
the same length)
data_type Values type (one of HC.xxx constants). All values
must be of the same type
vName Name of the vdata to create
vClass Vdata class (string)
Returns::
vdata reference number
C library equivalent : VHstoredata / VHstoredatam
"""
# See if the field is multi-valued.
nrecs = len(values)
if type(values[0]) in [list, tuple]:
order = len(values[0])
# Replace input list with a flattened list.
newValues = []
for el in values:
for e in el:
newValues.append(e)
values = newValues
else:
order = 1
n_values = nrecs * order
if data_type == HC.CHAR8:
buf = _C.array_byte(n_values)
# Allow values to be passed as a string.
# Noop if a list is passed.
values = list(values)
for n in range(n_values):
values[n] = ord(values[n])
elif data_type in [HC.UCHAR8, HC.UINT8]:
buf = _C.array_byte(n_values)
elif data_type == HC.INT8:
# SWIG refuses negative values here. We found that if we
# pass them as byte values, it will work.
buf = _C.array_int8(n_values)
values = list(values)
for n in range(n_values):
v = values[n]
if v >= 0:
v &= 0x7f
else:
v = abs(v) & 0x7f
if v:
v = 256 - v
else:
v = 128 # -128 in 2s complement
values[n] = v
elif data_type == HC.INT16:
buf = _C.array_int16(n_values)
elif data_type == HC.UINT16:
buf = _C.array_uint16(n_values)
elif data_type == HC.INT32:
buf = _C.array_int32(n_values)
elif data_type == HC.UINT32:
buf = _C.array_uint32(n_values)
elif data_type == HC.FLOAT32:
buf = _C.array_float32(n_values)
elif data_type == HC.FLOAT64:
buf = _C.array_float64(n_values)
else:
raise HDF4Error("storedata: illegal or unimplemented data_type")
for n in range(n_values):
buf[n] = values[n]
if order == 1:
vd = _C.VHstoredata(self._hdf_inst._id, fieldName, buf,
nrecs, data_type, vName, vClass)
else:
vd = _C.VHstoredatam(self._hdf_inst._id, fieldName, buf,
nrecs, data_type, vName, vClass, order)
_checkErr('storedata', vd, 'cannot create vdata')
return vd | python | def storedata(self, fieldName, values, data_type, vName, vClass):
"""Create and initialize a single field vdata, returning
the vdata reference number.
Args::
fieldName Name of the single field in the vadata to create
values Sequence of values to store in the field;. Each value can
itself be a sequence, in which case the field will be
multivalued (all second-level sequences must be of
the same length)
data_type Values type (one of HC.xxx constants). All values
must be of the same type
vName Name of the vdata to create
vClass Vdata class (string)
Returns::
vdata reference number
C library equivalent : VHstoredata / VHstoredatam
"""
# See if the field is multi-valued.
nrecs = len(values)
if type(values[0]) in [list, tuple]:
order = len(values[0])
# Replace input list with a flattened list.
newValues = []
for el in values:
for e in el:
newValues.append(e)
values = newValues
else:
order = 1
n_values = nrecs * order
if data_type == HC.CHAR8:
buf = _C.array_byte(n_values)
# Allow values to be passed as a string.
# Noop if a list is passed.
values = list(values)
for n in range(n_values):
values[n] = ord(values[n])
elif data_type in [HC.UCHAR8, HC.UINT8]:
buf = _C.array_byte(n_values)
elif data_type == HC.INT8:
# SWIG refuses negative values here. We found that if we
# pass them as byte values, it will work.
buf = _C.array_int8(n_values)
values = list(values)
for n in range(n_values):
v = values[n]
if v >= 0:
v &= 0x7f
else:
v = abs(v) & 0x7f
if v:
v = 256 - v
else:
v = 128 # -128 in 2s complement
values[n] = v
elif data_type == HC.INT16:
buf = _C.array_int16(n_values)
elif data_type == HC.UINT16:
buf = _C.array_uint16(n_values)
elif data_type == HC.INT32:
buf = _C.array_int32(n_values)
elif data_type == HC.UINT32:
buf = _C.array_uint32(n_values)
elif data_type == HC.FLOAT32:
buf = _C.array_float32(n_values)
elif data_type == HC.FLOAT64:
buf = _C.array_float64(n_values)
else:
raise HDF4Error("storedata: illegal or unimplemented data_type")
for n in range(n_values):
buf[n] = values[n]
if order == 1:
vd = _C.VHstoredata(self._hdf_inst._id, fieldName, buf,
nrecs, data_type, vName, vClass)
else:
vd = _C.VHstoredatam(self._hdf_inst._id, fieldName, buf,
nrecs, data_type, vName, vClass, order)
_checkErr('storedata', vd, 'cannot create vdata')
return vd | [
"def",
"storedata",
"(",
"self",
",",
"fieldName",
",",
"values",
",",
"data_type",
",",
"vName",
",",
"vClass",
")",
":",
"# See if the field is multi-valued.",
"nrecs",
"=",
"len",
"(",
"values",
")",
"if",
"type",
"(",
"values",
"[",
"0",
"]",
")",
"in",
"[",
"list",
",",
"tuple",
"]",
":",
"order",
"=",
"len",
"(",
"values",
"[",
"0",
"]",
")",
"# Replace input list with a flattened list.",
"newValues",
"=",
"[",
"]",
"for",
"el",
"in",
"values",
":",
"for",
"e",
"in",
"el",
":",
"newValues",
".",
"append",
"(",
"e",
")",
"values",
"=",
"newValues",
"else",
":",
"order",
"=",
"1",
"n_values",
"=",
"nrecs",
"*",
"order",
"if",
"data_type",
"==",
"HC",
".",
"CHAR8",
":",
"buf",
"=",
"_C",
".",
"array_byte",
"(",
"n_values",
")",
"# Allow values to be passed as a string.",
"# Noop if a list is passed.",
"values",
"=",
"list",
"(",
"values",
")",
"for",
"n",
"in",
"range",
"(",
"n_values",
")",
":",
"values",
"[",
"n",
"]",
"=",
"ord",
"(",
"values",
"[",
"n",
"]",
")",
"elif",
"data_type",
"in",
"[",
"HC",
".",
"UCHAR8",
",",
"HC",
".",
"UINT8",
"]",
":",
"buf",
"=",
"_C",
".",
"array_byte",
"(",
"n_values",
")",
"elif",
"data_type",
"==",
"HC",
".",
"INT8",
":",
"# SWIG refuses negative values here. We found that if we",
"# pass them as byte values, it will work.",
"buf",
"=",
"_C",
".",
"array_int8",
"(",
"n_values",
")",
"values",
"=",
"list",
"(",
"values",
")",
"for",
"n",
"in",
"range",
"(",
"n_values",
")",
":",
"v",
"=",
"values",
"[",
"n",
"]",
"if",
"v",
">=",
"0",
":",
"v",
"&=",
"0x7f",
"else",
":",
"v",
"=",
"abs",
"(",
"v",
")",
"&",
"0x7f",
"if",
"v",
":",
"v",
"=",
"256",
"-",
"v",
"else",
":",
"v",
"=",
"128",
"# -128 in 2s complement",
"values",
"[",
"n",
"]",
"=",
"v",
"elif",
"data_type",
"==",
"HC",
".",
"INT16",
":",
"buf",
"=",
"_C",
".",
"array_int16",
"(",
"n_values",
")",
"elif",
"data_type",
"==",
"HC",
".",
"UINT16",
":",
"buf",
"=",
"_C",
".",
"array_uint16",
"(",
"n_values",
")",
"elif",
"data_type",
"==",
"HC",
".",
"INT32",
":",
"buf",
"=",
"_C",
".",
"array_int32",
"(",
"n_values",
")",
"elif",
"data_type",
"==",
"HC",
".",
"UINT32",
":",
"buf",
"=",
"_C",
".",
"array_uint32",
"(",
"n_values",
")",
"elif",
"data_type",
"==",
"HC",
".",
"FLOAT32",
":",
"buf",
"=",
"_C",
".",
"array_float32",
"(",
"n_values",
")",
"elif",
"data_type",
"==",
"HC",
".",
"FLOAT64",
":",
"buf",
"=",
"_C",
".",
"array_float64",
"(",
"n_values",
")",
"else",
":",
"raise",
"HDF4Error",
"(",
"\"storedata: illegal or unimplemented data_type\"",
")",
"for",
"n",
"in",
"range",
"(",
"n_values",
")",
":",
"buf",
"[",
"n",
"]",
"=",
"values",
"[",
"n",
"]",
"if",
"order",
"==",
"1",
":",
"vd",
"=",
"_C",
".",
"VHstoredata",
"(",
"self",
".",
"_hdf_inst",
".",
"_id",
",",
"fieldName",
",",
"buf",
",",
"nrecs",
",",
"data_type",
",",
"vName",
",",
"vClass",
")",
"else",
":",
"vd",
"=",
"_C",
".",
"VHstoredatam",
"(",
"self",
".",
"_hdf_inst",
".",
"_id",
",",
"fieldName",
",",
"buf",
",",
"nrecs",
",",
"data_type",
",",
"vName",
",",
"vClass",
",",
"order",
")",
"_checkErr",
"(",
"'storedata'",
",",
"vd",
",",
"'cannot create vdata'",
")",
"return",
"vd"
] | Create and initialize a single field vdata, returning
the vdata reference number.
Args::
fieldName Name of the single field in the vadata to create
values Sequence of values to store in the field;. Each value can
itself be a sequence, in which case the field will be
multivalued (all second-level sequences must be of
the same length)
data_type Values type (one of HC.xxx constants). All values
must be of the same type
vName Name of the vdata to create
vClass Vdata class (string)
Returns::
vdata reference number
C library equivalent : VHstoredata / VHstoredatam | [
"Create",
"and",
"initialize",
"a",
"single",
"field",
"vdata",
"returning",
"the",
"vdata",
"reference",
"number",
"."
] | dbdc1810a74a38df50dcad81fe903e239d2b388d | https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/VS.py#L1062-L1159 | train | 237,400 |
fhs/pyhdf | pyhdf/VS.py | VD.field | def field(self, name_index):
"""Get a VDField instance representing a field of the vdata.
Args::
name_index name or index number of the field
Returns::
VDfield instance representing the field
C library equivalent : no equivalent
"""
# Transform a name to an index number
if isinstance(name_index, str):
status, index = _C.VSfindex(self._id, name_index)
_checkErr('field', status, "illegal field name: %s" % name_index)
else:
n = _C.VFnfields(self._id)
_checkErr('field', n, 'cannot execute')
index = name_index
if index >= n:
raise HDF4Error("field: illegal index number")
return VDField(self, index) | python | def field(self, name_index):
"""Get a VDField instance representing a field of the vdata.
Args::
name_index name or index number of the field
Returns::
VDfield instance representing the field
C library equivalent : no equivalent
"""
# Transform a name to an index number
if isinstance(name_index, str):
status, index = _C.VSfindex(self._id, name_index)
_checkErr('field', status, "illegal field name: %s" % name_index)
else:
n = _C.VFnfields(self._id)
_checkErr('field', n, 'cannot execute')
index = name_index
if index >= n:
raise HDF4Error("field: illegal index number")
return VDField(self, index) | [
"def",
"field",
"(",
"self",
",",
"name_index",
")",
":",
"# Transform a name to an index number",
"if",
"isinstance",
"(",
"name_index",
",",
"str",
")",
":",
"status",
",",
"index",
"=",
"_C",
".",
"VSfindex",
"(",
"self",
".",
"_id",
",",
"name_index",
")",
"_checkErr",
"(",
"'field'",
",",
"status",
",",
"\"illegal field name: %s\"",
"%",
"name_index",
")",
"else",
":",
"n",
"=",
"_C",
".",
"VFnfields",
"(",
"self",
".",
"_id",
")",
"_checkErr",
"(",
"'field'",
",",
"n",
",",
"'cannot execute'",
")",
"index",
"=",
"name_index",
"if",
"index",
">=",
"n",
":",
"raise",
"HDF4Error",
"(",
"\"field: illegal index number\"",
")",
"return",
"VDField",
"(",
"self",
",",
"index",
")"
] | Get a VDField instance representing a field of the vdata.
Args::
name_index name or index number of the field
Returns::
VDfield instance representing the field
C library equivalent : no equivalent | [
"Get",
"a",
"VDField",
"instance",
"representing",
"a",
"field",
"of",
"the",
"vdata",
"."
] | dbdc1810a74a38df50dcad81fe903e239d2b388d | https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/VS.py#L1480-L1504 | train | 237,401 |
fhs/pyhdf | pyhdf/VS.py | VD.seek | def seek(self, recIndex):
"""Seek to the beginning of the record identified by its
record index. A succeeding read will load this record in
memory.
Args::
recIndex index of the record in the vdata; numbering
starts at 0. Legal values range from 0
(start of vdata) to the current number of
records (at end of vdata).
Returns::
record index
An exception is raised if an attempt is made to seek beyond the
last record.
The C API prohibits seeking past the next-to-last record,
forcing one to read the last record to advance to the end
of the vdata. The python API removes this limitation.
Seeking to the end of the vdata can also be done by calling
method ``seekend()``.
C library equivalent : VSseek
"""
if recIndex > self._nrecs - 1:
if recIndex == self._nrecs:
return self.seekend()
else:
raise HDF4Error("attempt to seek past last record")
n = _C.VSseek(self._id, recIndex)
_checkErr('seek', n, 'cannot seek')
self._offset = n
return n | python | def seek(self, recIndex):
"""Seek to the beginning of the record identified by its
record index. A succeeding read will load this record in
memory.
Args::
recIndex index of the record in the vdata; numbering
starts at 0. Legal values range from 0
(start of vdata) to the current number of
records (at end of vdata).
Returns::
record index
An exception is raised if an attempt is made to seek beyond the
last record.
The C API prohibits seeking past the next-to-last record,
forcing one to read the last record to advance to the end
of the vdata. The python API removes this limitation.
Seeking to the end of the vdata can also be done by calling
method ``seekend()``.
C library equivalent : VSseek
"""
if recIndex > self._nrecs - 1:
if recIndex == self._nrecs:
return self.seekend()
else:
raise HDF4Error("attempt to seek past last record")
n = _C.VSseek(self._id, recIndex)
_checkErr('seek', n, 'cannot seek')
self._offset = n
return n | [
"def",
"seek",
"(",
"self",
",",
"recIndex",
")",
":",
"if",
"recIndex",
">",
"self",
".",
"_nrecs",
"-",
"1",
":",
"if",
"recIndex",
"==",
"self",
".",
"_nrecs",
":",
"return",
"self",
".",
"seekend",
"(",
")",
"else",
":",
"raise",
"HDF4Error",
"(",
"\"attempt to seek past last record\"",
")",
"n",
"=",
"_C",
".",
"VSseek",
"(",
"self",
".",
"_id",
",",
"recIndex",
")",
"_checkErr",
"(",
"'seek'",
",",
"n",
",",
"'cannot seek'",
")",
"self",
".",
"_offset",
"=",
"n",
"return",
"n"
] | Seek to the beginning of the record identified by its
record index. A succeeding read will load this record in
memory.
Args::
recIndex index of the record in the vdata; numbering
starts at 0. Legal values range from 0
(start of vdata) to the current number of
records (at end of vdata).
Returns::
record index
An exception is raised if an attempt is made to seek beyond the
last record.
The C API prohibits seeking past the next-to-last record,
forcing one to read the last record to advance to the end
of the vdata. The python API removes this limitation.
Seeking to the end of the vdata can also be done by calling
method ``seekend()``.
C library equivalent : VSseek | [
"Seek",
"to",
"the",
"beginning",
"of",
"the",
"record",
"identified",
"by",
"its",
"record",
"index",
".",
"A",
"succeeding",
"read",
"will",
"load",
"this",
"record",
"in",
"memory",
"."
] | dbdc1810a74a38df50dcad81fe903e239d2b388d | https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/VS.py#L1507-L1544 | train | 237,402 |
fhs/pyhdf | pyhdf/VS.py | VD.inquire | def inquire(self):
"""Retrieve info about the vdata.
Args::
no argument
Returns::
5-element tuple with the following elements:
-number of records in the vdata
-interlace mode
-list of vdata field names
-size in bytes of the vdata record
-name of the vdata
C library equivalent : VSinquire
"""
status, nRecs, interlace, fldNames, size, vName = \
_C.VSinquire(self._id)
_checkErr('inquire', status, "cannot query vdata info")
return nRecs, interlace, fldNames.split(','), size, vName | python | def inquire(self):
"""Retrieve info about the vdata.
Args::
no argument
Returns::
5-element tuple with the following elements:
-number of records in the vdata
-interlace mode
-list of vdata field names
-size in bytes of the vdata record
-name of the vdata
C library equivalent : VSinquire
"""
status, nRecs, interlace, fldNames, size, vName = \
_C.VSinquire(self._id)
_checkErr('inquire', status, "cannot query vdata info")
return nRecs, interlace, fldNames.split(','), size, vName | [
"def",
"inquire",
"(",
"self",
")",
":",
"status",
",",
"nRecs",
",",
"interlace",
",",
"fldNames",
",",
"size",
",",
"vName",
"=",
"_C",
".",
"VSinquire",
"(",
"self",
".",
"_id",
")",
"_checkErr",
"(",
"'inquire'",
",",
"status",
",",
"\"cannot query vdata info\"",
")",
"return",
"nRecs",
",",
"interlace",
",",
"fldNames",
".",
"split",
"(",
"','",
")",
",",
"size",
",",
"vName"
] | Retrieve info about the vdata.
Args::
no argument
Returns::
5-element tuple with the following elements:
-number of records in the vdata
-interlace mode
-list of vdata field names
-size in bytes of the vdata record
-name of the vdata
C library equivalent : VSinquire | [
"Retrieve",
"info",
"about",
"the",
"vdata",
"."
] | dbdc1810a74a38df50dcad81fe903e239d2b388d | https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/VS.py#L1861-L1883 | train | 237,403 |
fhs/pyhdf | pyhdf/VS.py | VD.fieldinfo | def fieldinfo(self):
"""Retrieve info about all vdata fields.
Args::
no argument
Returns::
list where each element describes a field of the vdata;
each field is described by an 7-element tuple containing
the following elements:
- field name
- field data type (one of HC.xxx constants)
- field order
- number of attributes attached to the field
- field index number
- field external size
- field internal size
C library equivalent : no equivalent
"""
lst = []
for n in range(self._nfields):
fld = self.field(n)
lst.append((fld._name,
fld._type,
fld._order,
fld._nattrs,
fld._index,
fld._esize,
fld._isize))
return lst | python | def fieldinfo(self):
"""Retrieve info about all vdata fields.
Args::
no argument
Returns::
list where each element describes a field of the vdata;
each field is described by an 7-element tuple containing
the following elements:
- field name
- field data type (one of HC.xxx constants)
- field order
- number of attributes attached to the field
- field index number
- field external size
- field internal size
C library equivalent : no equivalent
"""
lst = []
for n in range(self._nfields):
fld = self.field(n)
lst.append((fld._name,
fld._type,
fld._order,
fld._nattrs,
fld._index,
fld._esize,
fld._isize))
return lst | [
"def",
"fieldinfo",
"(",
"self",
")",
":",
"lst",
"=",
"[",
"]",
"for",
"n",
"in",
"range",
"(",
"self",
".",
"_nfields",
")",
":",
"fld",
"=",
"self",
".",
"field",
"(",
"n",
")",
"lst",
".",
"append",
"(",
"(",
"fld",
".",
"_name",
",",
"fld",
".",
"_type",
",",
"fld",
".",
"_order",
",",
"fld",
".",
"_nattrs",
",",
"fld",
".",
"_index",
",",
"fld",
".",
"_esize",
",",
"fld",
".",
"_isize",
")",
")",
"return",
"lst"
] | Retrieve info about all vdata fields.
Args::
no argument
Returns::
list where each element describes a field of the vdata;
each field is described by an 7-element tuple containing
the following elements:
- field name
- field data type (one of HC.xxx constants)
- field order
- number of attributes attached to the field
- field index number
- field external size
- field internal size
C library equivalent : no equivalent | [
"Retrieve",
"info",
"about",
"all",
"vdata",
"fields",
"."
] | dbdc1810a74a38df50dcad81fe903e239d2b388d | https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/VS.py#L1886-L1921 | train | 237,404 |
fhs/pyhdf | pyhdf/VS.py | VD.sizeof | def sizeof(self, fields):
"""Retrieve the size in bytes of the given fields.
Args::
fields sequence of field names to query
Returns::
total size of the fields in bytes
C library equivalent : VSsizeof
"""
if type(fields) in [tuple, list]:
str = ','.join(fields)
else:
str = fields
n = _C.VSsizeof(self._id, str)
_checkErr('sizeof', n, "cannot retrieve field sizes")
return n | python | def sizeof(self, fields):
"""Retrieve the size in bytes of the given fields.
Args::
fields sequence of field names to query
Returns::
total size of the fields in bytes
C library equivalent : VSsizeof
"""
if type(fields) in [tuple, list]:
str = ','.join(fields)
else:
str = fields
n = _C.VSsizeof(self._id, str)
_checkErr('sizeof', n, "cannot retrieve field sizes")
return n | [
"def",
"sizeof",
"(",
"self",
",",
"fields",
")",
":",
"if",
"type",
"(",
"fields",
")",
"in",
"[",
"tuple",
",",
"list",
"]",
":",
"str",
"=",
"','",
".",
"join",
"(",
"fields",
")",
"else",
":",
"str",
"=",
"fields",
"n",
"=",
"_C",
".",
"VSsizeof",
"(",
"self",
".",
"_id",
",",
"str",
")",
"_checkErr",
"(",
"'sizeof'",
",",
"n",
",",
"\"cannot retrieve field sizes\"",
")",
"return",
"n"
] | Retrieve the size in bytes of the given fields.
Args::
fields sequence of field names to query
Returns::
total size of the fields in bytes
C library equivalent : VSsizeof | [
"Retrieve",
"the",
"size",
"in",
"bytes",
"of",
"the",
"given",
"fields",
"."
] | dbdc1810a74a38df50dcad81fe903e239d2b388d | https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/VS.py#L1923-L1943 | train | 237,405 |
fhs/pyhdf | pyhdf/VS.py | VD.fexist | def fexist(self, fields):
"""Check if a vdata contains a given set of fields.
Args::
fields sequence of field names whose presence in the
vdata must be checked
Returns::
true (1) if the given fields are present
false (0) otherwise
C library equivalent : VSfexist
"""
if type(fields) in [tuple, list]:
str = ','.join(fields)
else:
str = fields
ret = _C.VSfexist(self._id, str)
if ret < 0:
return 0
else:
return 1 | python | def fexist(self, fields):
"""Check if a vdata contains a given set of fields.
Args::
fields sequence of field names whose presence in the
vdata must be checked
Returns::
true (1) if the given fields are present
false (0) otherwise
C library equivalent : VSfexist
"""
if type(fields) in [tuple, list]:
str = ','.join(fields)
else:
str = fields
ret = _C.VSfexist(self._id, str)
if ret < 0:
return 0
else:
return 1 | [
"def",
"fexist",
"(",
"self",
",",
"fields",
")",
":",
"if",
"type",
"(",
"fields",
")",
"in",
"[",
"tuple",
",",
"list",
"]",
":",
"str",
"=",
"','",
".",
"join",
"(",
"fields",
")",
"else",
":",
"str",
"=",
"fields",
"ret",
"=",
"_C",
".",
"VSfexist",
"(",
"self",
".",
"_id",
",",
"str",
")",
"if",
"ret",
"<",
"0",
":",
"return",
"0",
"else",
":",
"return",
"1"
] | Check if a vdata contains a given set of fields.
Args::
fields sequence of field names whose presence in the
vdata must be checked
Returns::
true (1) if the given fields are present
false (0) otherwise
C library equivalent : VSfexist | [
"Check",
"if",
"a",
"vdata",
"contains",
"a",
"given",
"set",
"of",
"fields",
"."
] | dbdc1810a74a38df50dcad81fe903e239d2b388d | https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/VS.py#L1945-L1969 | train | 237,406 |
fhs/pyhdf | pyhdf/VS.py | VDField.find | def find(self, name):
"""Search the field for a given attribute.
Args::
name attribute name
Returns::
if found, VDAttr instance describing the attribute
None otherwise
C library equivalent : VSfindattr
"""
try:
att = self.attr(name)
if att._index is None:
att = None
except HDF4Error:
att = None
return att | python | def find(self, name):
"""Search the field for a given attribute.
Args::
name attribute name
Returns::
if found, VDAttr instance describing the attribute
None otherwise
C library equivalent : VSfindattr
"""
try:
att = self.attr(name)
if att._index is None:
att = None
except HDF4Error:
att = None
return att | [
"def",
"find",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"att",
"=",
"self",
".",
"attr",
"(",
"name",
")",
"if",
"att",
".",
"_index",
"is",
"None",
":",
"att",
"=",
"None",
"except",
"HDF4Error",
":",
"att",
"=",
"None",
"return",
"att"
] | Search the field for a given attribute.
Args::
name attribute name
Returns::
if found, VDAttr instance describing the attribute
None otherwise
C library equivalent : VSfindattr | [
"Search",
"the",
"field",
"for",
"a",
"given",
"attribute",
"."
] | dbdc1810a74a38df50dcad81fe903e239d2b388d | https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/VS.py#L2236-L2257 | train | 237,407 |
fhs/pyhdf | pyhdf/VS.py | VDAttr.set | def set(self, data_type, values):
"""Set the attribute value.
Args::
data_type : attribute data type (see constants HC.xxx)
values : attribute value(s); specify a list to create
a multi-valued attribute; a string valued
attribute can be created by setting 'data_type'
to HC.CHAR8 and 'values' to the corresponding
string
If the attribute already exists, it will be
updated. However, it is illegal to try to change
its data type or its order (number of values).
Returns::
None
C library equivalent : VSsetattr
"""
try:
n_values = len(values)
except:
values = [values]
n_values = 1
if data_type == HC.CHAR8:
buf = _C.array_byte(n_values)
# Allow values to be passed as a string.
# Noop if a list is passed.
values = list(values)
for n in range(n_values):
if not isinstance(values[n], int):
values[n] = ord(values[n])
elif data_type in [HC.UCHAR8, HC.UINT8]:
buf = _C.array_byte(n_values)
elif data_type == HC.INT8:
# SWIG refuses negative values here. We found that if we
# pass them as byte values, it will work.
buf = _C.array_int8(n_values)
values = list(values)
for n in range(n_values):
v = values[n]
if v >= 0:
v &= 0x7f
else:
v = abs(v) & 0x7f
if v:
v = 256 - v
else:
v = 128 # -128 in 2s complement
values[n] = v
elif data_type == HC.INT16:
buf = _C.array_int16(n_values)
elif data_type == HC.UINT16:
buf = _C.array_uint16(n_values)
elif data_type == HC.INT32:
buf = _C.array_int32(n_values)
elif data_type == HC.UINT32:
buf = _C.array_uint32(n_values)
elif data_type == HC.FLOAT32:
buf = _C.array_float32(n_values)
elif data_type == HC.FLOAT64:
buf = _C.array_float64(n_values)
else:
raise HDF4Error("set: illegal or unimplemented data_type")
for n in range(n_values):
buf[n] = values[n]
status = _C.VSsetattr(self._vd_inst._id, self._fIndex, self._name,
data_type, n_values, buf)
_checkErr('attr', status, 'cannot execute')
# Update the attribute index
self._index = _C.VSfindattr(self._vd_inst._id, self._fIndex,
self._name);
if self._index < 0:
raise HDF4Error("set: error retrieving attribute index") | python | def set(self, data_type, values):
"""Set the attribute value.
Args::
data_type : attribute data type (see constants HC.xxx)
values : attribute value(s); specify a list to create
a multi-valued attribute; a string valued
attribute can be created by setting 'data_type'
to HC.CHAR8 and 'values' to the corresponding
string
If the attribute already exists, it will be
updated. However, it is illegal to try to change
its data type or its order (number of values).
Returns::
None
C library equivalent : VSsetattr
"""
try:
n_values = len(values)
except:
values = [values]
n_values = 1
if data_type == HC.CHAR8:
buf = _C.array_byte(n_values)
# Allow values to be passed as a string.
# Noop if a list is passed.
values = list(values)
for n in range(n_values):
if not isinstance(values[n], int):
values[n] = ord(values[n])
elif data_type in [HC.UCHAR8, HC.UINT8]:
buf = _C.array_byte(n_values)
elif data_type == HC.INT8:
# SWIG refuses negative values here. We found that if we
# pass them as byte values, it will work.
buf = _C.array_int8(n_values)
values = list(values)
for n in range(n_values):
v = values[n]
if v >= 0:
v &= 0x7f
else:
v = abs(v) & 0x7f
if v:
v = 256 - v
else:
v = 128 # -128 in 2s complement
values[n] = v
elif data_type == HC.INT16:
buf = _C.array_int16(n_values)
elif data_type == HC.UINT16:
buf = _C.array_uint16(n_values)
elif data_type == HC.INT32:
buf = _C.array_int32(n_values)
elif data_type == HC.UINT32:
buf = _C.array_uint32(n_values)
elif data_type == HC.FLOAT32:
buf = _C.array_float32(n_values)
elif data_type == HC.FLOAT64:
buf = _C.array_float64(n_values)
else:
raise HDF4Error("set: illegal or unimplemented data_type")
for n in range(n_values):
buf[n] = values[n]
status = _C.VSsetattr(self._vd_inst._id, self._fIndex, self._name,
data_type, n_values, buf)
_checkErr('attr', status, 'cannot execute')
# Update the attribute index
self._index = _C.VSfindattr(self._vd_inst._id, self._fIndex,
self._name);
if self._index < 0:
raise HDF4Error("set: error retrieving attribute index") | [
"def",
"set",
"(",
"self",
",",
"data_type",
",",
"values",
")",
":",
"try",
":",
"n_values",
"=",
"len",
"(",
"values",
")",
"except",
":",
"values",
"=",
"[",
"values",
"]",
"n_values",
"=",
"1",
"if",
"data_type",
"==",
"HC",
".",
"CHAR8",
":",
"buf",
"=",
"_C",
".",
"array_byte",
"(",
"n_values",
")",
"# Allow values to be passed as a string.",
"# Noop if a list is passed.",
"values",
"=",
"list",
"(",
"values",
")",
"for",
"n",
"in",
"range",
"(",
"n_values",
")",
":",
"if",
"not",
"isinstance",
"(",
"values",
"[",
"n",
"]",
",",
"int",
")",
":",
"values",
"[",
"n",
"]",
"=",
"ord",
"(",
"values",
"[",
"n",
"]",
")",
"elif",
"data_type",
"in",
"[",
"HC",
".",
"UCHAR8",
",",
"HC",
".",
"UINT8",
"]",
":",
"buf",
"=",
"_C",
".",
"array_byte",
"(",
"n_values",
")",
"elif",
"data_type",
"==",
"HC",
".",
"INT8",
":",
"# SWIG refuses negative values here. We found that if we",
"# pass them as byte values, it will work.",
"buf",
"=",
"_C",
".",
"array_int8",
"(",
"n_values",
")",
"values",
"=",
"list",
"(",
"values",
")",
"for",
"n",
"in",
"range",
"(",
"n_values",
")",
":",
"v",
"=",
"values",
"[",
"n",
"]",
"if",
"v",
">=",
"0",
":",
"v",
"&=",
"0x7f",
"else",
":",
"v",
"=",
"abs",
"(",
"v",
")",
"&",
"0x7f",
"if",
"v",
":",
"v",
"=",
"256",
"-",
"v",
"else",
":",
"v",
"=",
"128",
"# -128 in 2s complement",
"values",
"[",
"n",
"]",
"=",
"v",
"elif",
"data_type",
"==",
"HC",
".",
"INT16",
":",
"buf",
"=",
"_C",
".",
"array_int16",
"(",
"n_values",
")",
"elif",
"data_type",
"==",
"HC",
".",
"UINT16",
":",
"buf",
"=",
"_C",
".",
"array_uint16",
"(",
"n_values",
")",
"elif",
"data_type",
"==",
"HC",
".",
"INT32",
":",
"buf",
"=",
"_C",
".",
"array_int32",
"(",
"n_values",
")",
"elif",
"data_type",
"==",
"HC",
".",
"UINT32",
":",
"buf",
"=",
"_C",
".",
"array_uint32",
"(",
"n_values",
")",
"elif",
"data_type",
"==",
"HC",
".",
"FLOAT32",
":",
"buf",
"=",
"_C",
".",
"array_float32",
"(",
"n_values",
")",
"elif",
"data_type",
"==",
"HC",
".",
"FLOAT64",
":",
"buf",
"=",
"_C",
".",
"array_float64",
"(",
"n_values",
")",
"else",
":",
"raise",
"HDF4Error",
"(",
"\"set: illegal or unimplemented data_type\"",
")",
"for",
"n",
"in",
"range",
"(",
"n_values",
")",
":",
"buf",
"[",
"n",
"]",
"=",
"values",
"[",
"n",
"]",
"status",
"=",
"_C",
".",
"VSsetattr",
"(",
"self",
".",
"_vd_inst",
".",
"_id",
",",
"self",
".",
"_fIndex",
",",
"self",
".",
"_name",
",",
"data_type",
",",
"n_values",
",",
"buf",
")",
"_checkErr",
"(",
"'attr'",
",",
"status",
",",
"'cannot execute'",
")",
"# Update the attribute index",
"self",
".",
"_index",
"=",
"_C",
".",
"VSfindattr",
"(",
"self",
".",
"_vd_inst",
".",
"_id",
",",
"self",
".",
"_fIndex",
",",
"self",
".",
"_name",
")",
"if",
"self",
".",
"_index",
"<",
"0",
":",
"raise",
"HDF4Error",
"(",
"\"set: error retrieving attribute index\"",
")"
] | Set the attribute value.
Args::
data_type : attribute data type (see constants HC.xxx)
values : attribute value(s); specify a list to create
a multi-valued attribute; a string valued
attribute can be created by setting 'data_type'
to HC.CHAR8 and 'values' to the corresponding
string
If the attribute already exists, it will be
updated. However, it is illegal to try to change
its data type or its order (number of values).
Returns::
None
C library equivalent : VSsetattr | [
"Set",
"the",
"attribute",
"value",
"."
] | dbdc1810a74a38df50dcad81fe903e239d2b388d | https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/VS.py#L2406-L2493 | train | 237,408 |
fhs/pyhdf | pyhdf/HDF.py | getlibversion | def getlibversion():
"""Get the library version info.
Args:
no argument
Returns:
4-element tuple with the following components:
-major version number (int)
-minor version number (int)
-complete library version number (int)
-additional information (string)
C library equivalent : Hgetlibversion
"""
status, major_v, minor_v, release, info = _C.Hgetlibversion()
_checkErr('getlibversion', status, "cannot get lib version")
return major_v, minor_v, release, info | python | def getlibversion():
"""Get the library version info.
Args:
no argument
Returns:
4-element tuple with the following components:
-major version number (int)
-minor version number (int)
-complete library version number (int)
-additional information (string)
C library equivalent : Hgetlibversion
"""
status, major_v, minor_v, release, info = _C.Hgetlibversion()
_checkErr('getlibversion', status, "cannot get lib version")
return major_v, minor_v, release, info | [
"def",
"getlibversion",
"(",
")",
":",
"status",
",",
"major_v",
",",
"minor_v",
",",
"release",
",",
"info",
"=",
"_C",
".",
"Hgetlibversion",
"(",
")",
"_checkErr",
"(",
"'getlibversion'",
",",
"status",
",",
"\"cannot get lib version\"",
")",
"return",
"major_v",
",",
"minor_v",
",",
"release",
",",
"info"
] | Get the library version info.
Args:
no argument
Returns:
4-element tuple with the following components:
-major version number (int)
-minor version number (int)
-complete library version number (int)
-additional information (string)
C library equivalent : Hgetlibversion | [
"Get",
"the",
"library",
"version",
"info",
"."
] | dbdc1810a74a38df50dcad81fe903e239d2b388d | https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/HDF.py#L99-L116 | train | 237,409 |
fhs/pyhdf | pyhdf/HDF.py | HDF.getfileversion | def getfileversion(self):
"""Get file version info.
Args:
no argument
Returns:
4-element tuple with the following components:
-major version number (int)
-minor version number (int)
-complete library version number (int)
-additional information (string)
C library equivalent : Hgetlibversion
"""
status, major_v, minor_v, release, info = _C.Hgetfileversion(self._id)
_checkErr('getfileversion', status, "cannot get file version")
return major_v, minor_v, release, info | python | def getfileversion(self):
"""Get file version info.
Args:
no argument
Returns:
4-element tuple with the following components:
-major version number (int)
-minor version number (int)
-complete library version number (int)
-additional information (string)
C library equivalent : Hgetlibversion
"""
status, major_v, minor_v, release, info = _C.Hgetfileversion(self._id)
_checkErr('getfileversion', status, "cannot get file version")
return major_v, minor_v, release, info | [
"def",
"getfileversion",
"(",
"self",
")",
":",
"status",
",",
"major_v",
",",
"minor_v",
",",
"release",
",",
"info",
"=",
"_C",
".",
"Hgetfileversion",
"(",
"self",
".",
"_id",
")",
"_checkErr",
"(",
"'getfileversion'",
",",
"status",
",",
"\"cannot get file version\"",
")",
"return",
"major_v",
",",
"minor_v",
",",
"release",
",",
"info"
] | Get file version info.
Args:
no argument
Returns:
4-element tuple with the following components:
-major version number (int)
-minor version number (int)
-complete library version number (int)
-additional information (string)
C library equivalent : Hgetlibversion | [
"Get",
"file",
"version",
"info",
"."
] | dbdc1810a74a38df50dcad81fe903e239d2b388d | https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/HDF.py#L244-L261 | train | 237,410 |
mattmakai/underwear | underwear/run_underwear.py | colorize | def colorize(lead, num, color):
""" Print 'lead' = 'num' in 'color' """
if num != 0 and ANSIBLE_COLOR and color is not None:
return "%s%s%-15s" % (stringc(lead, color), stringc("=", color), stringc(str(num), color))
else:
return "%s=%-4s" % (lead, str(num)) | python | def colorize(lead, num, color):
""" Print 'lead' = 'num' in 'color' """
if num != 0 and ANSIBLE_COLOR and color is not None:
return "%s%s%-15s" % (stringc(lead, color), stringc("=", color), stringc(str(num), color))
else:
return "%s=%-4s" % (lead, str(num)) | [
"def",
"colorize",
"(",
"lead",
",",
"num",
",",
"color",
")",
":",
"if",
"num",
"!=",
"0",
"and",
"ANSIBLE_COLOR",
"and",
"color",
"is",
"not",
"None",
":",
"return",
"\"%s%s%-15s\"",
"%",
"(",
"stringc",
"(",
"lead",
",",
"color",
")",
",",
"stringc",
"(",
"\"=\"",
",",
"color",
")",
",",
"stringc",
"(",
"str",
"(",
"num",
")",
",",
"color",
")",
")",
"else",
":",
"return",
"\"%s=%-4s\"",
"%",
"(",
"lead",
",",
"str",
"(",
"num",
")",
")"
] | Print 'lead' = 'num' in 'color' | [
"Print",
"lead",
"=",
"num",
"in",
"color"
] | 7c484c7937d2df86dc569d411249ba366ed43ead | https://github.com/mattmakai/underwear/blob/7c484c7937d2df86dc569d411249ba366ed43ead/underwear/run_underwear.py#L24-L29 | train | 237,411 |
zapier/django-drip | drip/admin.py | DripAdmin.timeline | def timeline(self, request, drip_id, into_past, into_future):
"""
Return a list of people who should get emails.
"""
from django.shortcuts import render, get_object_or_404
drip = get_object_or_404(Drip, id=drip_id)
shifted_drips = []
seen_users = set()
for shifted_drip in drip.drip.walk(into_past=int(into_past), into_future=int(into_future)+1):
shifted_drip.prune()
shifted_drips.append({
'drip': shifted_drip,
'qs': shifted_drip.get_queryset().exclude(id__in=seen_users)
})
seen_users.update(shifted_drip.get_queryset().values_list('id', flat=True))
return render(request, 'drip/timeline.html', locals()) | python | def timeline(self, request, drip_id, into_past, into_future):
"""
Return a list of people who should get emails.
"""
from django.shortcuts import render, get_object_or_404
drip = get_object_or_404(Drip, id=drip_id)
shifted_drips = []
seen_users = set()
for shifted_drip in drip.drip.walk(into_past=int(into_past), into_future=int(into_future)+1):
shifted_drip.prune()
shifted_drips.append({
'drip': shifted_drip,
'qs': shifted_drip.get_queryset().exclude(id__in=seen_users)
})
seen_users.update(shifted_drip.get_queryset().values_list('id', flat=True))
return render(request, 'drip/timeline.html', locals()) | [
"def",
"timeline",
"(",
"self",
",",
"request",
",",
"drip_id",
",",
"into_past",
",",
"into_future",
")",
":",
"from",
"django",
".",
"shortcuts",
"import",
"render",
",",
"get_object_or_404",
"drip",
"=",
"get_object_or_404",
"(",
"Drip",
",",
"id",
"=",
"drip_id",
")",
"shifted_drips",
"=",
"[",
"]",
"seen_users",
"=",
"set",
"(",
")",
"for",
"shifted_drip",
"in",
"drip",
".",
"drip",
".",
"walk",
"(",
"into_past",
"=",
"int",
"(",
"into_past",
")",
",",
"into_future",
"=",
"int",
"(",
"into_future",
")",
"+",
"1",
")",
":",
"shifted_drip",
".",
"prune",
"(",
")",
"shifted_drips",
".",
"append",
"(",
"{",
"'drip'",
":",
"shifted_drip",
",",
"'qs'",
":",
"shifted_drip",
".",
"get_queryset",
"(",
")",
".",
"exclude",
"(",
"id__in",
"=",
"seen_users",
")",
"}",
")",
"seen_users",
".",
"update",
"(",
"shifted_drip",
".",
"get_queryset",
"(",
")",
".",
"values_list",
"(",
"'id'",
",",
"flat",
"=",
"True",
")",
")",
"return",
"render",
"(",
"request",
",",
"'drip/timeline.html'",
",",
"locals",
"(",
")",
")"
] | Return a list of people who should get emails. | [
"Return",
"a",
"list",
"of",
"people",
"who",
"should",
"get",
"emails",
"."
] | ffbef6927a1a20f4c353ecb108c1b484502d2b29 | https://github.com/zapier/django-drip/blob/ffbef6927a1a20f4c353ecb108c1b484502d2b29/drip/admin.py#L33-L51 | train | 237,412 |
zapier/django-drip | drip/drips.py | DripBase.walk | def walk(self, into_past=0, into_future=0):
"""
Walk over a date range and create new instances of self with new ranges.
"""
walked_range = []
for shift in range(-into_past, into_future):
kwargs = dict(drip_model=self.drip_model,
name=self.name,
now_shift_kwargs={'days': shift})
walked_range.append(self.__class__(**kwargs))
return walked_range | python | def walk(self, into_past=0, into_future=0):
"""
Walk over a date range and create new instances of self with new ranges.
"""
walked_range = []
for shift in range(-into_past, into_future):
kwargs = dict(drip_model=self.drip_model,
name=self.name,
now_shift_kwargs={'days': shift})
walked_range.append(self.__class__(**kwargs))
return walked_range | [
"def",
"walk",
"(",
"self",
",",
"into_past",
"=",
"0",
",",
"into_future",
"=",
"0",
")",
":",
"walked_range",
"=",
"[",
"]",
"for",
"shift",
"in",
"range",
"(",
"-",
"into_past",
",",
"into_future",
")",
":",
"kwargs",
"=",
"dict",
"(",
"drip_model",
"=",
"self",
".",
"drip_model",
",",
"name",
"=",
"self",
".",
"name",
",",
"now_shift_kwargs",
"=",
"{",
"'days'",
":",
"shift",
"}",
")",
"walked_range",
".",
"append",
"(",
"self",
".",
"__class__",
"(",
"*",
"*",
"kwargs",
")",
")",
"return",
"walked_range"
] | Walk over a date range and create new instances of self with new ranges. | [
"Walk",
"over",
"a",
"date",
"range",
"and",
"create",
"new",
"instances",
"of",
"self",
"with",
"new",
"ranges",
"."
] | ffbef6927a1a20f4c353ecb108c1b484502d2b29 | https://github.com/zapier/django-drip/blob/ffbef6927a1a20f4c353ecb108c1b484502d2b29/drip/drips.py#L146-L156 | train | 237,413 |
zapier/django-drip | drip/drips.py | DripBase.run | def run(self):
"""
Get the queryset, prune sent people, and send it.
"""
if not self.drip_model.enabled:
return None
self.prune()
count = self.send()
return count | python | def run(self):
"""
Get the queryset, prune sent people, and send it.
"""
if not self.drip_model.enabled:
return None
self.prune()
count = self.send()
return count | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"drip_model",
".",
"enabled",
":",
"return",
"None",
"self",
".",
"prune",
"(",
")",
"count",
"=",
"self",
".",
"send",
"(",
")",
"return",
"count"
] | Get the queryset, prune sent people, and send it. | [
"Get",
"the",
"queryset",
"prune",
"sent",
"people",
"and",
"send",
"it",
"."
] | ffbef6927a1a20f4c353ecb108c1b484502d2b29 | https://github.com/zapier/django-drip/blob/ffbef6927a1a20f4c353ecb108c1b484502d2b29/drip/drips.py#L194-L204 | train | 237,414 |
zapier/django-drip | drip/drips.py | DripBase.prune | def prune(self):
"""
Do an exclude for all Users who have a SentDrip already.
"""
target_user_ids = self.get_queryset().values_list('id', flat=True)
exclude_user_ids = SentDrip.objects.filter(date__lt=conditional_now(),
drip=self.drip_model,
user__id__in=target_user_ids)\
.values_list('user_id', flat=True)
self._queryset = self.get_queryset().exclude(id__in=exclude_user_ids) | python | def prune(self):
"""
Do an exclude for all Users who have a SentDrip already.
"""
target_user_ids = self.get_queryset().values_list('id', flat=True)
exclude_user_ids = SentDrip.objects.filter(date__lt=conditional_now(),
drip=self.drip_model,
user__id__in=target_user_ids)\
.values_list('user_id', flat=True)
self._queryset = self.get_queryset().exclude(id__in=exclude_user_ids) | [
"def",
"prune",
"(",
"self",
")",
":",
"target_user_ids",
"=",
"self",
".",
"get_queryset",
"(",
")",
".",
"values_list",
"(",
"'id'",
",",
"flat",
"=",
"True",
")",
"exclude_user_ids",
"=",
"SentDrip",
".",
"objects",
".",
"filter",
"(",
"date__lt",
"=",
"conditional_now",
"(",
")",
",",
"drip",
"=",
"self",
".",
"drip_model",
",",
"user__id__in",
"=",
"target_user_ids",
")",
".",
"values_list",
"(",
"'user_id'",
",",
"flat",
"=",
"True",
")",
"self",
".",
"_queryset",
"=",
"self",
".",
"get_queryset",
"(",
")",
".",
"exclude",
"(",
"id__in",
"=",
"exclude_user_ids",
")"
] | Do an exclude for all Users who have a SentDrip already. | [
"Do",
"an",
"exclude",
"for",
"all",
"Users",
"who",
"have",
"a",
"SentDrip",
"already",
"."
] | ffbef6927a1a20f4c353ecb108c1b484502d2b29 | https://github.com/zapier/django-drip/blob/ffbef6927a1a20f4c353ecb108c1b484502d2b29/drip/drips.py#L206-L215 | train | 237,415 |
zapier/django-drip | drip/drips.py | DripBase.send | def send(self):
"""
Send the message to each user on the queryset.
Create SentDrip for each user that gets a message.
Returns count of created SentDrips.
"""
if not self.from_email:
self.from_email = getattr(settings, 'DRIP_FROM_EMAIL', settings.DEFAULT_FROM_EMAIL)
MessageClass = message_class_for(self.drip_model.message_class)
count = 0
for user in self.get_queryset():
message_instance = MessageClass(self, user)
try:
result = message_instance.message.send()
if result:
SentDrip.objects.create(
drip=self.drip_model,
user=user,
from_email=self.from_email,
from_email_name=self.from_email_name,
subject=message_instance.subject,
body=message_instance.body
)
count += 1
except Exception as e:
logging.error("Failed to send drip %s to user %s: %s" % (self.drip_model.id, user, e))
return count | python | def send(self):
"""
Send the message to each user on the queryset.
Create SentDrip for each user that gets a message.
Returns count of created SentDrips.
"""
if not self.from_email:
self.from_email = getattr(settings, 'DRIP_FROM_EMAIL', settings.DEFAULT_FROM_EMAIL)
MessageClass = message_class_for(self.drip_model.message_class)
count = 0
for user in self.get_queryset():
message_instance = MessageClass(self, user)
try:
result = message_instance.message.send()
if result:
SentDrip.objects.create(
drip=self.drip_model,
user=user,
from_email=self.from_email,
from_email_name=self.from_email_name,
subject=message_instance.subject,
body=message_instance.body
)
count += 1
except Exception as e:
logging.error("Failed to send drip %s to user %s: %s" % (self.drip_model.id, user, e))
return count | [
"def",
"send",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"from_email",
":",
"self",
".",
"from_email",
"=",
"getattr",
"(",
"settings",
",",
"'DRIP_FROM_EMAIL'",
",",
"settings",
".",
"DEFAULT_FROM_EMAIL",
")",
"MessageClass",
"=",
"message_class_for",
"(",
"self",
".",
"drip_model",
".",
"message_class",
")",
"count",
"=",
"0",
"for",
"user",
"in",
"self",
".",
"get_queryset",
"(",
")",
":",
"message_instance",
"=",
"MessageClass",
"(",
"self",
",",
"user",
")",
"try",
":",
"result",
"=",
"message_instance",
".",
"message",
".",
"send",
"(",
")",
"if",
"result",
":",
"SentDrip",
".",
"objects",
".",
"create",
"(",
"drip",
"=",
"self",
".",
"drip_model",
",",
"user",
"=",
"user",
",",
"from_email",
"=",
"self",
".",
"from_email",
",",
"from_email_name",
"=",
"self",
".",
"from_email_name",
",",
"subject",
"=",
"message_instance",
".",
"subject",
",",
"body",
"=",
"message_instance",
".",
"body",
")",
"count",
"+=",
"1",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"\"Failed to send drip %s to user %s: %s\"",
"%",
"(",
"self",
".",
"drip_model",
".",
"id",
",",
"user",
",",
"e",
")",
")",
"return",
"count"
] | Send the message to each user on the queryset.
Create SentDrip for each user that gets a message.
Returns count of created SentDrips. | [
"Send",
"the",
"message",
"to",
"each",
"user",
"on",
"the",
"queryset",
"."
] | ffbef6927a1a20f4c353ecb108c1b484502d2b29 | https://github.com/zapier/django-drip/blob/ffbef6927a1a20f4c353ecb108c1b484502d2b29/drip/drips.py#L217-L248 | train | 237,416 |
ladybug-tools/ladybug | ladybug/euclid.py | Vector2.angle | def angle(self, other):
"""Return the angle to the vector other"""
return math.acos(self.dot(other) / (self.magnitude() * other.magnitude())) | python | def angle(self, other):
"""Return the angle to the vector other"""
return math.acos(self.dot(other) / (self.magnitude() * other.magnitude())) | [
"def",
"angle",
"(",
"self",
",",
"other",
")",
":",
"return",
"math",
".",
"acos",
"(",
"self",
".",
"dot",
"(",
"other",
")",
"/",
"(",
"self",
".",
"magnitude",
"(",
")",
"*",
"other",
".",
"magnitude",
"(",
")",
")",
")"
] | Return the angle to the vector other | [
"Return",
"the",
"angle",
"to",
"the",
"vector",
"other"
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/euclid.py#L298-L300 | train | 237,417 |
ladybug-tools/ladybug | ladybug/euclid.py | Vector2.project | def project(self, other):
"""Return one vector projected on the vector other"""
n = other.normalized()
return self.dot(n) * n | python | def project(self, other):
"""Return one vector projected on the vector other"""
n = other.normalized()
return self.dot(n) * n | [
"def",
"project",
"(",
"self",
",",
"other",
")",
":",
"n",
"=",
"other",
".",
"normalized",
"(",
")",
"return",
"self",
".",
"dot",
"(",
"n",
")",
"*",
"n"
] | Return one vector projected on the vector other | [
"Return",
"one",
"vector",
"projected",
"on",
"the",
"vector",
"other"
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/euclid.py#L302-L305 | train | 237,418 |
ladybug-tools/ladybug | ladybug/euclid.py | Vector3.rotate_around | def rotate_around(self, axis, theta):
"""Return the vector rotated around axis through angle theta.
Right hand rule applies.
"""
# Adapted from equations published by Glenn Murray.
# http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/ArbitraryAxisRotation.html
x, y, z = self.x, self.y, self.z
u, v, w = axis.x, axis.y, axis.z
# Extracted common factors for simplicity and efficiency
r2 = u**2 + v**2 + w**2
r = math.sqrt(r2)
ct = math.cos(theta)
st = math.sin(theta) / r
dt = (u * x + v * y + w * z) * (1 - ct) / r2
return Vector3((u * dt + x * ct + (-w * y + v * z) * st),
(v * dt + y * ct + (w * x - u * z) * st),
(w * dt + z * ct + (-v * x + u * y) * st)) | python | def rotate_around(self, axis, theta):
"""Return the vector rotated around axis through angle theta.
Right hand rule applies.
"""
# Adapted from equations published by Glenn Murray.
# http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/ArbitraryAxisRotation.html
x, y, z = self.x, self.y, self.z
u, v, w = axis.x, axis.y, axis.z
# Extracted common factors for simplicity and efficiency
r2 = u**2 + v**2 + w**2
r = math.sqrt(r2)
ct = math.cos(theta)
st = math.sin(theta) / r
dt = (u * x + v * y + w * z) * (1 - ct) / r2
return Vector3((u * dt + x * ct + (-w * y + v * z) * st),
(v * dt + y * ct + (w * x - u * z) * st),
(w * dt + z * ct + (-v * x + u * y) * st)) | [
"def",
"rotate_around",
"(",
"self",
",",
"axis",
",",
"theta",
")",
":",
"# Adapted from equations published by Glenn Murray.",
"# http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/ArbitraryAxisRotation.html",
"x",
",",
"y",
",",
"z",
"=",
"self",
".",
"x",
",",
"self",
".",
"y",
",",
"self",
".",
"z",
"u",
",",
"v",
",",
"w",
"=",
"axis",
".",
"x",
",",
"axis",
".",
"y",
",",
"axis",
".",
"z",
"# Extracted common factors for simplicity and efficiency",
"r2",
"=",
"u",
"**",
"2",
"+",
"v",
"**",
"2",
"+",
"w",
"**",
"2",
"r",
"=",
"math",
".",
"sqrt",
"(",
"r2",
")",
"ct",
"=",
"math",
".",
"cos",
"(",
"theta",
")",
"st",
"=",
"math",
".",
"sin",
"(",
"theta",
")",
"/",
"r",
"dt",
"=",
"(",
"u",
"*",
"x",
"+",
"v",
"*",
"y",
"+",
"w",
"*",
"z",
")",
"*",
"(",
"1",
"-",
"ct",
")",
"/",
"r2",
"return",
"Vector3",
"(",
"(",
"u",
"*",
"dt",
"+",
"x",
"*",
"ct",
"+",
"(",
"-",
"w",
"*",
"y",
"+",
"v",
"*",
"z",
")",
"*",
"st",
")",
",",
"(",
"v",
"*",
"dt",
"+",
"y",
"*",
"ct",
"+",
"(",
"w",
"*",
"x",
"-",
"u",
"*",
"z",
")",
"*",
"st",
")",
",",
"(",
"w",
"*",
"dt",
"+",
"z",
"*",
"ct",
"+",
"(",
"-",
"v",
"*",
"x",
"+",
"u",
"*",
"y",
")",
"*",
"st",
")",
")"
] | Return the vector rotated around axis through angle theta.
Right hand rule applies. | [
"Return",
"the",
"vector",
"rotated",
"around",
"axis",
"through",
"angle",
"theta",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/euclid.py#L588-L607 | train | 237,419 |
ladybug-tools/ladybug | ladybug/futil.py | preparedir | def preparedir(target_dir, remove_content=True):
"""Prepare a folder for analysis.
This method creates the folder if it is not created, and removes the file in
the folder if the folder already existed.
"""
if os.path.isdir(target_dir):
if remove_content:
nukedir(target_dir, False)
return True
else:
try:
os.makedirs(target_dir)
return True
except Exception as e:
print("Failed to create folder: %s\n%s" % (target_dir, e))
return False | python | def preparedir(target_dir, remove_content=True):
"""Prepare a folder for analysis.
This method creates the folder if it is not created, and removes the file in
the folder if the folder already existed.
"""
if os.path.isdir(target_dir):
if remove_content:
nukedir(target_dir, False)
return True
else:
try:
os.makedirs(target_dir)
return True
except Exception as e:
print("Failed to create folder: %s\n%s" % (target_dir, e))
return False | [
"def",
"preparedir",
"(",
"target_dir",
",",
"remove_content",
"=",
"True",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"target_dir",
")",
":",
"if",
"remove_content",
":",
"nukedir",
"(",
"target_dir",
",",
"False",
")",
"return",
"True",
"else",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"target_dir",
")",
"return",
"True",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\"Failed to create folder: %s\\n%s\"",
"%",
"(",
"target_dir",
",",
"e",
")",
")",
"return",
"False"
] | Prepare a folder for analysis.
This method creates the folder if it is not created, and removes the file in
the folder if the folder already existed. | [
"Prepare",
"a",
"folder",
"for",
"analysis",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/futil.py#L20-L36 | train | 237,420 |
ladybug-tools/ladybug | ladybug/futil.py | nukedir | def nukedir(target_dir, rmdir=False):
"""Delete all the files inside target_dir.
Usage:
nukedir("c:/ladybug/libs", True)
"""
d = os.path.normpath(target_dir)
if not os.path.isdir(d):
return
files = os.listdir(d)
for f in files:
if f == '.' or f == '..':
continue
path = os.path.join(d, f)
if os.path.isdir(path):
nukedir(path)
else:
try:
os.remove(path)
except Exception:
print("Failed to remove %s" % path)
if rmdir:
try:
os.rmdir(d)
except Exception:
print("Failed to remove %s" % d) | python | def nukedir(target_dir, rmdir=False):
"""Delete all the files inside target_dir.
Usage:
nukedir("c:/ladybug/libs", True)
"""
d = os.path.normpath(target_dir)
if not os.path.isdir(d):
return
files = os.listdir(d)
for f in files:
if f == '.' or f == '..':
continue
path = os.path.join(d, f)
if os.path.isdir(path):
nukedir(path)
else:
try:
os.remove(path)
except Exception:
print("Failed to remove %s" % path)
if rmdir:
try:
os.rmdir(d)
except Exception:
print("Failed to remove %s" % d) | [
"def",
"nukedir",
"(",
"target_dir",
",",
"rmdir",
"=",
"False",
")",
":",
"d",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"target_dir",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"d",
")",
":",
"return",
"files",
"=",
"os",
".",
"listdir",
"(",
"d",
")",
"for",
"f",
"in",
"files",
":",
"if",
"f",
"==",
"'.'",
"or",
"f",
"==",
"'..'",
":",
"continue",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"f",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"nukedir",
"(",
"path",
")",
"else",
":",
"try",
":",
"os",
".",
"remove",
"(",
"path",
")",
"except",
"Exception",
":",
"print",
"(",
"\"Failed to remove %s\"",
"%",
"path",
")",
"if",
"rmdir",
":",
"try",
":",
"os",
".",
"rmdir",
"(",
"d",
")",
"except",
"Exception",
":",
"print",
"(",
"\"Failed to remove %s\"",
"%",
"d",
")"
] | Delete all the files inside target_dir.
Usage:
nukedir("c:/ladybug/libs", True) | [
"Delete",
"all",
"the",
"files",
"inside",
"target_dir",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/futil.py#L39-L69 | train | 237,421 |
ladybug-tools/ladybug | ladybug/futil.py | write_to_file_by_name | def write_to_file_by_name(folder, fname, data, mkdir=False):
"""Write a string of data to file by filename and folder.
Args:
folder: Target folder (e.g. c:/ladybug).
fname: File name (e.g. testPts.pts).
data: Any data as string.
mkdir: Set to True to create the directory if doesn't exist (Default: False).
"""
if not os.path.isdir(folder):
if mkdir:
preparedir(folder)
else:
created = preparedir(folder, False)
if not created:
raise ValueError("Failed to find %s." % folder)
file_path = os.path.join(folder, fname)
with open(file_path, writemode) as outf:
try:
outf.write(str(data))
return file_path
except Exception as e:
raise IOError("Failed to write %s to file:\n\t%s" % (fname, str(e))) | python | def write_to_file_by_name(folder, fname, data, mkdir=False):
"""Write a string of data to file by filename and folder.
Args:
folder: Target folder (e.g. c:/ladybug).
fname: File name (e.g. testPts.pts).
data: Any data as string.
mkdir: Set to True to create the directory if doesn't exist (Default: False).
"""
if not os.path.isdir(folder):
if mkdir:
preparedir(folder)
else:
created = preparedir(folder, False)
if not created:
raise ValueError("Failed to find %s." % folder)
file_path = os.path.join(folder, fname)
with open(file_path, writemode) as outf:
try:
outf.write(str(data))
return file_path
except Exception as e:
raise IOError("Failed to write %s to file:\n\t%s" % (fname, str(e))) | [
"def",
"write_to_file_by_name",
"(",
"folder",
",",
"fname",
",",
"data",
",",
"mkdir",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"folder",
")",
":",
"if",
"mkdir",
":",
"preparedir",
"(",
"folder",
")",
"else",
":",
"created",
"=",
"preparedir",
"(",
"folder",
",",
"False",
")",
"if",
"not",
"created",
":",
"raise",
"ValueError",
"(",
"\"Failed to find %s.\"",
"%",
"folder",
")",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"fname",
")",
"with",
"open",
"(",
"file_path",
",",
"writemode",
")",
"as",
"outf",
":",
"try",
":",
"outf",
".",
"write",
"(",
"str",
"(",
"data",
")",
")",
"return",
"file_path",
"except",
"Exception",
"as",
"e",
":",
"raise",
"IOError",
"(",
"\"Failed to write %s to file:\\n\\t%s\"",
"%",
"(",
"fname",
",",
"str",
"(",
"e",
")",
")",
")"
] | Write a string of data to file by filename and folder.
Args:
folder: Target folder (e.g. c:/ladybug).
fname: File name (e.g. testPts.pts).
data: Any data as string.
mkdir: Set to True to create the directory if doesn't exist (Default: False). | [
"Write",
"a",
"string",
"of",
"data",
"to",
"file",
"by",
"filename",
"and",
"folder",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/futil.py#L72-L96 | train | 237,422 |
ladybug-tools/ladybug | ladybug/futil.py | copy_files_to_folder | def copy_files_to_folder(files, target_folder, overwrite=True):
"""Copy a list of files to a new target folder.
Returns:
A list of fullpath of the new files.
"""
if not files:
return []
for f in files:
target = os.path.join(target_folder, os.path.split(f)[-1])
if target == f:
# both file path are the same!
return target
if os.path.exists(target):
if overwrite:
# remove the file before copying
try:
os.remove(target)
except Exception:
raise IOError("Failed to remove %s" % f)
else:
shutil.copy(f, target)
else:
continue
else:
print('Copying %s to %s' % (os.path.split(f)[-1],
os.path.normpath(target_folder)))
shutil.copy(f, target)
return [os.path.join(target_folder, os.path.split(f)[-1]) for f in files] | python | def copy_files_to_folder(files, target_folder, overwrite=True):
"""Copy a list of files to a new target folder.
Returns:
A list of fullpath of the new files.
"""
if not files:
return []
for f in files:
target = os.path.join(target_folder, os.path.split(f)[-1])
if target == f:
# both file path are the same!
return target
if os.path.exists(target):
if overwrite:
# remove the file before copying
try:
os.remove(target)
except Exception:
raise IOError("Failed to remove %s" % f)
else:
shutil.copy(f, target)
else:
continue
else:
print('Copying %s to %s' % (os.path.split(f)[-1],
os.path.normpath(target_folder)))
shutil.copy(f, target)
return [os.path.join(target_folder, os.path.split(f)[-1]) for f in files] | [
"def",
"copy_files_to_folder",
"(",
"files",
",",
"target_folder",
",",
"overwrite",
"=",
"True",
")",
":",
"if",
"not",
"files",
":",
"return",
"[",
"]",
"for",
"f",
"in",
"files",
":",
"target",
"=",
"os",
".",
"path",
".",
"join",
"(",
"target_folder",
",",
"os",
".",
"path",
".",
"split",
"(",
"f",
")",
"[",
"-",
"1",
"]",
")",
"if",
"target",
"==",
"f",
":",
"# both file path are the same!",
"return",
"target",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"target",
")",
":",
"if",
"overwrite",
":",
"# remove the file before copying",
"try",
":",
"os",
".",
"remove",
"(",
"target",
")",
"except",
"Exception",
":",
"raise",
"IOError",
"(",
"\"Failed to remove %s\"",
"%",
"f",
")",
"else",
":",
"shutil",
".",
"copy",
"(",
"f",
",",
"target",
")",
"else",
":",
"continue",
"else",
":",
"print",
"(",
"'Copying %s to %s'",
"%",
"(",
"os",
".",
"path",
".",
"split",
"(",
"f",
")",
"[",
"-",
"1",
"]",
",",
"os",
".",
"path",
".",
"normpath",
"(",
"target_folder",
")",
")",
")",
"shutil",
".",
"copy",
"(",
"f",
",",
"target",
")",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"target_folder",
",",
"os",
".",
"path",
".",
"split",
"(",
"f",
")",
"[",
"-",
"1",
"]",
")",
"for",
"f",
"in",
"files",
"]"
] | Copy a list of files to a new target folder.
Returns:
A list of fullpath of the new files. | [
"Copy",
"a",
"list",
"of",
"files",
"to",
"a",
"new",
"target",
"folder",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/futil.py#L111-L143 | train | 237,423 |
ladybug-tools/ladybug | ladybug/futil.py | bat_to_sh | def bat_to_sh(file_path):
"""Convert honeybee .bat file to .sh file.
WARNING: This is a very simple function and doesn't handle any edge cases.
"""
sh_file = file_path[:-4] + '.sh'
with open(file_path, 'rb') as inf, open(sh_file, 'wb') as outf:
outf.write('#!/usr/bin/env bash\n\n')
for line in inf:
# pass the path lines, etc to get to the commands
if line.strip():
continue
else:
break
for line in inf:
if line.startswith('echo'):
continue
modified_line = line.replace('c:\\radiance\\bin\\', '').replace('\\', '/')
outf.write(modified_line)
print('bash file is created at:\n\t%s' % sh_file)
# Heroku - Make command.sh executable
st = os.stat(sh_file)
os.chmod(sh_file, st.st_mode | 0o111)
return sh_file | python | def bat_to_sh(file_path):
"""Convert honeybee .bat file to .sh file.
WARNING: This is a very simple function and doesn't handle any edge cases.
"""
sh_file = file_path[:-4] + '.sh'
with open(file_path, 'rb') as inf, open(sh_file, 'wb') as outf:
outf.write('#!/usr/bin/env bash\n\n')
for line in inf:
# pass the path lines, etc to get to the commands
if line.strip():
continue
else:
break
for line in inf:
if line.startswith('echo'):
continue
modified_line = line.replace('c:\\radiance\\bin\\', '').replace('\\', '/')
outf.write(modified_line)
print('bash file is created at:\n\t%s' % sh_file)
# Heroku - Make command.sh executable
st = os.stat(sh_file)
os.chmod(sh_file, st.st_mode | 0o111)
return sh_file | [
"def",
"bat_to_sh",
"(",
"file_path",
")",
":",
"sh_file",
"=",
"file_path",
"[",
":",
"-",
"4",
"]",
"+",
"'.sh'",
"with",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"as",
"inf",
",",
"open",
"(",
"sh_file",
",",
"'wb'",
")",
"as",
"outf",
":",
"outf",
".",
"write",
"(",
"'#!/usr/bin/env bash\\n\\n'",
")",
"for",
"line",
"in",
"inf",
":",
"# pass the path lines, etc to get to the commands",
"if",
"line",
".",
"strip",
"(",
")",
":",
"continue",
"else",
":",
"break",
"for",
"line",
"in",
"inf",
":",
"if",
"line",
".",
"startswith",
"(",
"'echo'",
")",
":",
"continue",
"modified_line",
"=",
"line",
".",
"replace",
"(",
"'c:\\\\radiance\\\\bin\\\\'",
",",
"''",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"outf",
".",
"write",
"(",
"modified_line",
")",
"print",
"(",
"'bash file is created at:\\n\\t%s'",
"%",
"sh_file",
")",
"# Heroku - Make command.sh executable",
"st",
"=",
"os",
".",
"stat",
"(",
"sh_file",
")",
"os",
".",
"chmod",
"(",
"sh_file",
",",
"st",
".",
"st_mode",
"|",
"0o111",
")",
"return",
"sh_file"
] | Convert honeybee .bat file to .sh file.
WARNING: This is a very simple function and doesn't handle any edge cases. | [
"Convert",
"honeybee",
".",
"bat",
"file",
"to",
".",
"sh",
"file",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/futil.py#L146-L171 | train | 237,424 |
ladybug-tools/ladybug | ladybug/futil.py | _download_py2 | def _download_py2(link, path, __hdr__):
"""Download a file from a link in Python 2."""
try:
req = urllib2.Request(link, headers=__hdr__)
u = urllib2.urlopen(req)
except Exception as e:
raise Exception(' Download failed with the error:\n{}'.format(e))
with open(path, 'wb') as outf:
for l in u:
outf.write(l)
u.close() | python | def _download_py2(link, path, __hdr__):
"""Download a file from a link in Python 2."""
try:
req = urllib2.Request(link, headers=__hdr__)
u = urllib2.urlopen(req)
except Exception as e:
raise Exception(' Download failed with the error:\n{}'.format(e))
with open(path, 'wb') as outf:
for l in u:
outf.write(l)
u.close() | [
"def",
"_download_py2",
"(",
"link",
",",
"path",
",",
"__hdr__",
")",
":",
"try",
":",
"req",
"=",
"urllib2",
".",
"Request",
"(",
"link",
",",
"headers",
"=",
"__hdr__",
")",
"u",
"=",
"urllib2",
".",
"urlopen",
"(",
"req",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"Exception",
"(",
"' Download failed with the error:\\n{}'",
".",
"format",
"(",
"e",
")",
")",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"outf",
":",
"for",
"l",
"in",
"u",
":",
"outf",
".",
"write",
"(",
"l",
")",
"u",
".",
"close",
"(",
")"
] | Download a file from a link in Python 2. | [
"Download",
"a",
"file",
"from",
"a",
"link",
"in",
"Python",
"2",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/futil.py#L174-L185 | train | 237,425 |
ladybug-tools/ladybug | ladybug/futil.py | _download_py3 | def _download_py3(link, path, __hdr__):
"""Download a file from a link in Python 3."""
try:
req = urllib.request.Request(link, headers=__hdr__)
u = urllib.request.urlopen(req)
except Exception as e:
raise Exception(' Download failed with the error:\n{}'.format(e))
with open(path, 'wb') as outf:
for l in u:
outf.write(l)
u.close() | python | def _download_py3(link, path, __hdr__):
"""Download a file from a link in Python 3."""
try:
req = urllib.request.Request(link, headers=__hdr__)
u = urllib.request.urlopen(req)
except Exception as e:
raise Exception(' Download failed with the error:\n{}'.format(e))
with open(path, 'wb') as outf:
for l in u:
outf.write(l)
u.close() | [
"def",
"_download_py3",
"(",
"link",
",",
"path",
",",
"__hdr__",
")",
":",
"try",
":",
"req",
"=",
"urllib",
".",
"request",
".",
"Request",
"(",
"link",
",",
"headers",
"=",
"__hdr__",
")",
"u",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"req",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"Exception",
"(",
"' Download failed with the error:\\n{}'",
".",
"format",
"(",
"e",
")",
")",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"outf",
":",
"for",
"l",
"in",
"u",
":",
"outf",
".",
"write",
"(",
"l",
")",
"u",
".",
"close",
"(",
")"
] | Download a file from a link in Python 3. | [
"Download",
"a",
"file",
"from",
"a",
"link",
"in",
"Python",
"3",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/futil.py#L188-L199 | train | 237,426 |
ladybug-tools/ladybug | ladybug/futil.py | download_file_by_name | def download_file_by_name(url, target_folder, file_name, mkdir=False):
"""Download a file to a directory.
Args:
url: A string to a valid URL.
target_folder: Target folder for download (e.g. c:/ladybug)
file_name: File name (e.g. testPts.zip).
mkdir: Set to True to create the directory if doesn't exist (Default: False)
"""
# headers to "spoof" the download as coming from a browser (needed for E+ site)
__hdr__ = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 '
'(KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,'
'application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
# create the target directory.
if not os.path.isdir(target_folder):
if mkdir:
preparedir(target_folder)
else:
created = preparedir(target_folder, False)
if not created:
raise ValueError("Failed to find %s." % target_folder)
file_path = os.path.join(target_folder, file_name)
if (sys.version_info < (3, 0)):
_download_py2(url, file_path, __hdr__)
else:
_download_py3(url, file_path, __hdr__) | python | def download_file_by_name(url, target_folder, file_name, mkdir=False):
"""Download a file to a directory.
Args:
url: A string to a valid URL.
target_folder: Target folder for download (e.g. c:/ladybug)
file_name: File name (e.g. testPts.zip).
mkdir: Set to True to create the directory if doesn't exist (Default: False)
"""
# headers to "spoof" the download as coming from a browser (needed for E+ site)
__hdr__ = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 '
'(KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,'
'application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
# create the target directory.
if not os.path.isdir(target_folder):
if mkdir:
preparedir(target_folder)
else:
created = preparedir(target_folder, False)
if not created:
raise ValueError("Failed to find %s." % target_folder)
file_path = os.path.join(target_folder, file_name)
if (sys.version_info < (3, 0)):
_download_py2(url, file_path, __hdr__)
else:
_download_py3(url, file_path, __hdr__) | [
"def",
"download_file_by_name",
"(",
"url",
",",
"target_folder",
",",
"file_name",
",",
"mkdir",
"=",
"False",
")",
":",
"# headers to \"spoof\" the download as coming from a browser (needed for E+ site)",
"__hdr__",
"=",
"{",
"'User-Agent'",
":",
"'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 '",
"'(KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'",
",",
"'Accept'",
":",
"'text/html,application/xhtml+xml,'",
"'application/xml;q=0.9,*/*;q=0.8'",
",",
"'Accept-Charset'",
":",
"'ISO-8859-1,utf-8;q=0.7,*;q=0.3'",
",",
"'Accept-Encoding'",
":",
"'none'",
",",
"'Accept-Language'",
":",
"'en-US,en;q=0.8'",
",",
"'Connection'",
":",
"'keep-alive'",
"}",
"# create the target directory.",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"target_folder",
")",
":",
"if",
"mkdir",
":",
"preparedir",
"(",
"target_folder",
")",
"else",
":",
"created",
"=",
"preparedir",
"(",
"target_folder",
",",
"False",
")",
"if",
"not",
"created",
":",
"raise",
"ValueError",
"(",
"\"Failed to find %s.\"",
"%",
"target_folder",
")",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"target_folder",
",",
"file_name",
")",
"if",
"(",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
")",
":",
"_download_py2",
"(",
"url",
",",
"file_path",
",",
"__hdr__",
")",
"else",
":",
"_download_py3",
"(",
"url",
",",
"file_path",
",",
"__hdr__",
")"
] | Download a file to a directory.
Args:
url: A string to a valid URL.
target_folder: Target folder for download (e.g. c:/ladybug)
file_name: File name (e.g. testPts.zip).
mkdir: Set to True to create the directory if doesn't exist (Default: False) | [
"Download",
"a",
"file",
"to",
"a",
"directory",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/futil.py#L202-L234 | train | 237,427 |
ladybug-tools/ladybug | ladybug/futil.py | unzip_file | def unzip_file(source_file, dest_dir=None, mkdir=False):
"""Unzip a compressed file.
Args:
source_file: Full path to a valid compressed file (e.g. c:/ladybug/testPts.zip)
dest_dir: Target folder to extract to (e.g. c:/ladybug).
Default is set to the same directory as the source file.
mkdir: Set to True to create the directory if doesn't exist (Default: False)
"""
# set default dest_dir and create it if need be.
if dest_dir is None:
dest_dir, fname = os.path.split(source_file)
elif not os.path.isdir(dest_dir):
if mkdir:
preparedir(dest_dir)
else:
created = preparedir(dest_dir, False)
if not created:
raise ValueError("Failed to find %s." % dest_dir)
# extract files to destination
with zipfile.ZipFile(source_file) as zf:
for member in zf.infolist():
words = member.filename.split('\\')
for word in words[:-1]:
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if word in (os.curdir, os.pardir, ''):
continue
dest_dir = os.path.join(dest_dir, word)
zf.extract(member, dest_dir) | python | def unzip_file(source_file, dest_dir=None, mkdir=False):
"""Unzip a compressed file.
Args:
source_file: Full path to a valid compressed file (e.g. c:/ladybug/testPts.zip)
dest_dir: Target folder to extract to (e.g. c:/ladybug).
Default is set to the same directory as the source file.
mkdir: Set to True to create the directory if doesn't exist (Default: False)
"""
# set default dest_dir and create it if need be.
if dest_dir is None:
dest_dir, fname = os.path.split(source_file)
elif not os.path.isdir(dest_dir):
if mkdir:
preparedir(dest_dir)
else:
created = preparedir(dest_dir, False)
if not created:
raise ValueError("Failed to find %s." % dest_dir)
# extract files to destination
with zipfile.ZipFile(source_file) as zf:
for member in zf.infolist():
words = member.filename.split('\\')
for word in words[:-1]:
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if word in (os.curdir, os.pardir, ''):
continue
dest_dir = os.path.join(dest_dir, word)
zf.extract(member, dest_dir) | [
"def",
"unzip_file",
"(",
"source_file",
",",
"dest_dir",
"=",
"None",
",",
"mkdir",
"=",
"False",
")",
":",
"# set default dest_dir and create it if need be.",
"if",
"dest_dir",
"is",
"None",
":",
"dest_dir",
",",
"fname",
"=",
"os",
".",
"path",
".",
"split",
"(",
"source_file",
")",
"elif",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dest_dir",
")",
":",
"if",
"mkdir",
":",
"preparedir",
"(",
"dest_dir",
")",
"else",
":",
"created",
"=",
"preparedir",
"(",
"dest_dir",
",",
"False",
")",
"if",
"not",
"created",
":",
"raise",
"ValueError",
"(",
"\"Failed to find %s.\"",
"%",
"dest_dir",
")",
"# extract files to destination",
"with",
"zipfile",
".",
"ZipFile",
"(",
"source_file",
")",
"as",
"zf",
":",
"for",
"member",
"in",
"zf",
".",
"infolist",
"(",
")",
":",
"words",
"=",
"member",
".",
"filename",
".",
"split",
"(",
"'\\\\'",
")",
"for",
"word",
"in",
"words",
"[",
":",
"-",
"1",
"]",
":",
"drive",
",",
"word",
"=",
"os",
".",
"path",
".",
"splitdrive",
"(",
"word",
")",
"head",
",",
"word",
"=",
"os",
".",
"path",
".",
"split",
"(",
"word",
")",
"if",
"word",
"in",
"(",
"os",
".",
"curdir",
",",
"os",
".",
"pardir",
",",
"''",
")",
":",
"continue",
"dest_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dest_dir",
",",
"word",
")",
"zf",
".",
"extract",
"(",
"member",
",",
"dest_dir",
")"
] | Unzip a compressed file.
Args:
source_file: Full path to a valid compressed file (e.g. c:/ladybug/testPts.zip)
dest_dir: Target folder to extract to (e.g. c:/ladybug).
Default is set to the same directory as the source file.
mkdir: Set to True to create the directory if doesn't exist (Default: False) | [
"Unzip",
"a",
"compressed",
"file",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/futil.py#L249-L279 | train | 237,428 |
ladybug-tools/ladybug | ladybug/futil.py | csv_to_matrix | def csv_to_matrix(csv_file_path):
"""Load a CSV file into a Python matrix of strings.
Args:
csv_file_path: Full path to a valid CSV file (e.g. c:/ladybug/test.csv)
"""
mtx = []
with open(csv_file_path) as csv_data_file:
for row in csv_data_file:
mtx.append(row.split(','))
return mtx | python | def csv_to_matrix(csv_file_path):
"""Load a CSV file into a Python matrix of strings.
Args:
csv_file_path: Full path to a valid CSV file (e.g. c:/ladybug/test.csv)
"""
mtx = []
with open(csv_file_path) as csv_data_file:
for row in csv_data_file:
mtx.append(row.split(','))
return mtx | [
"def",
"csv_to_matrix",
"(",
"csv_file_path",
")",
":",
"mtx",
"=",
"[",
"]",
"with",
"open",
"(",
"csv_file_path",
")",
"as",
"csv_data_file",
":",
"for",
"row",
"in",
"csv_data_file",
":",
"mtx",
".",
"append",
"(",
"row",
".",
"split",
"(",
"','",
")",
")",
"return",
"mtx"
] | Load a CSV file into a Python matrix of strings.
Args:
csv_file_path: Full path to a valid CSV file (e.g. c:/ladybug/test.csv) | [
"Load",
"a",
"CSV",
"file",
"into",
"a",
"Python",
"matrix",
"of",
"strings",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/futil.py#L282-L292 | train | 237,429 |
ladybug-tools/ladybug | ladybug/futil.py | csv_to_num_matrix | def csv_to_num_matrix(csv_file_path):
"""Load a CSV file consisting only of numbers into a Python matrix of floats.
Args:
csv_file_path: Full path to a valid CSV file (e.g. c:/ladybug/test.csv)
"""
mtx = []
with open(csv_file_path) as csv_data_file:
for row in csv_data_file:
mtx.append([float(val) for val in row.split(',')])
return mtx | python | def csv_to_num_matrix(csv_file_path):
"""Load a CSV file consisting only of numbers into a Python matrix of floats.
Args:
csv_file_path: Full path to a valid CSV file (e.g. c:/ladybug/test.csv)
"""
mtx = []
with open(csv_file_path) as csv_data_file:
for row in csv_data_file:
mtx.append([float(val) for val in row.split(',')])
return mtx | [
"def",
"csv_to_num_matrix",
"(",
"csv_file_path",
")",
":",
"mtx",
"=",
"[",
"]",
"with",
"open",
"(",
"csv_file_path",
")",
"as",
"csv_data_file",
":",
"for",
"row",
"in",
"csv_data_file",
":",
"mtx",
".",
"append",
"(",
"[",
"float",
"(",
"val",
")",
"for",
"val",
"in",
"row",
".",
"split",
"(",
"','",
")",
"]",
")",
"return",
"mtx"
] | Load a CSV file consisting only of numbers into a Python matrix of floats.
Args:
csv_file_path: Full path to a valid CSV file (e.g. c:/ladybug/test.csv) | [
"Load",
"a",
"CSV",
"file",
"consisting",
"only",
"of",
"numbers",
"into",
"a",
"Python",
"matrix",
"of",
"floats",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/futil.py#L295-L305 | train | 237,430 |
ladybug-tools/ladybug | ladybug/stat.py | STAT.from_json | def from_json(cls, data):
""" Create STAT from json dictionary.
Args:
data: {
'location': {} , // ladybug location schema
'ashrae_climate_zone': str,
'koppen_climate_zone': str,
'extreme_cold_week': {}, // ladybug analysis period schema
'extreme_hot_week': {}, // ladybug analysis period schema
'typical_weeks': {}, // dict of ladybug analysis period schemas
'heating_dict': {}, // dict containing heating design conditions
'cooling_dict': {}, // dict containing cooling design conditions
"monthly_db_50": [], // list of 12 float values for each month
"monthly_wb_50": [], // list of 12 float values for each month
"monthly_db_range_50": [], // list of 12 float values for each month
"monthly_wb_range_50": [], // list of 12 float values for each month
"monthly_db_100": [], // list of 12 float values for each month
"monthly_wb_100": [], // list of 12 float values for each month
"monthly_db_20": [], // list of 12 float values for each month
"monthly_wb_20": [], // list of 12 float values for each month
"monthly_db_04": [], // list of 12 float values for each month
"monthly_wb_04": [], // list of 12 float values for each month
"monthly_wind": [], // list of 12 float values for each month
"monthly_wind_dirs": [], // matrix with 12 cols for months of the year
and 8 rows for the cardinal directions.
"standard_pressure_at_elev": float, // float value for pressure in Pa
"monthly_tau_beam":[], // list of 12 float values for each month
"monthly_tau_diffuse": [] // list of 12 float values for each month
}
"""
# Initialize the class with all data missing
stat_ob = cls(None)
# Check required and optional keys
option_keys_none = ('ashrae_climate_zone', 'koppen_climate_zone',
'extreme_cold_week', 'extreme_hot_week',
'standard_pressure_at_elev')
option_keys_list = ('monthly_db_50', 'monthly_wb_50',
'monthly_db_range_50', 'monthly_wb_range_50',
'monthly_db_100', 'monthly_wb_100', 'monthly_db_20',
'monthly_wb_20', 'monthly_db_04', 'monthly_wb_04',
'monthly_wind', 'monthly_wind_dirs',
'monthly_tau_beam', 'monthly_tau_diffuse')
option_keys_dict = ('typical_weeks', 'heating_dict', 'cooling_dict')
assert 'location' in data, 'Required key "location" is missing!'
for key in option_keys_none:
if key not in data:
data[key] = None
for key in option_keys_list:
if key not in data:
data[key] = []
for key in option_keys_dict:
if key not in data:
data[key] = {}
# assign the properties of the dictionary to the stat object.
stat_ob._location = Location.from_json(data['location'])
stat_ob._ashrae_climate_zone = data['ashrae_climate_zone']
stat_ob._koppen_climate_zone = data['koppen_climate_zone']
stat_ob._extreme_cold_week = AnalysisPeriod.from_json(data['extreme_cold_week'])\
if data['extreme_cold_week'] else None
stat_ob._extreme_hot_week = AnalysisPeriod.from_json(data['extreme_hot_week'])\
if data['extreme_hot_week'] else None
stat_ob._typical_weeks = {}
for key, val in data['typical_weeks'].items():
if isinstance(val, list):
stat_ob._typical_weeks[key] = [AnalysisPeriod.from_json(v) for v in val]
else:
stat_ob._typical_weeks[key] = AnalysisPeriod.from_json(val)
stat_ob._winter_des_day_dict = data['heating_dict']
stat_ob._summer_des_day_dict = data['cooling_dict']
stat_ob._monthly_db_50 = data['monthly_db_50']
stat_ob._monthly_wb_50 = data['monthly_wb_50']
stat_ob._monthly_db_range_50 = data['monthly_db_range_50']
stat_ob._monthly_wb_range_50 = data['monthly_wb_range_50']
stat_ob._monthly_db_100 = data['monthly_db_100']
stat_ob._monthly_wb_100 = data['monthly_wb_100']
stat_ob._monthly_db_20 = data['monthly_db_20']
stat_ob._monthly_wb_20 = data['monthly_wb_20']
stat_ob._monthly_db_04 = data['monthly_db_04']
stat_ob._monthly_wb_04 = data['monthly_wb_04']
stat_ob._monthly_wind = data['monthly_wind']
stat_ob._monthly_wind_dirs = data['monthly_wind_dirs']
stat_ob._stand_press_at_elev = data['standard_pressure_at_elev']
stat_ob._monthly_tau_beam = data['monthly_tau_beam']
stat_ob._monthly_tau_diffuse = data['monthly_tau_diffuse']
return stat_ob | python | def from_json(cls, data):
""" Create STAT from json dictionary.
Args:
data: {
'location': {} , // ladybug location schema
'ashrae_climate_zone': str,
'koppen_climate_zone': str,
'extreme_cold_week': {}, // ladybug analysis period schema
'extreme_hot_week': {}, // ladybug analysis period schema
'typical_weeks': {}, // dict of ladybug analysis period schemas
'heating_dict': {}, // dict containing heating design conditions
'cooling_dict': {}, // dict containing cooling design conditions
"monthly_db_50": [], // list of 12 float values for each month
"monthly_wb_50": [], // list of 12 float values for each month
"monthly_db_range_50": [], // list of 12 float values for each month
"monthly_wb_range_50": [], // list of 12 float values for each month
"monthly_db_100": [], // list of 12 float values for each month
"monthly_wb_100": [], // list of 12 float values for each month
"monthly_db_20": [], // list of 12 float values for each month
"monthly_wb_20": [], // list of 12 float values for each month
"monthly_db_04": [], // list of 12 float values for each month
"monthly_wb_04": [], // list of 12 float values for each month
"monthly_wind": [], // list of 12 float values for each month
"monthly_wind_dirs": [], // matrix with 12 cols for months of the year
and 8 rows for the cardinal directions.
"standard_pressure_at_elev": float, // float value for pressure in Pa
"monthly_tau_beam":[], // list of 12 float values for each month
"monthly_tau_diffuse": [] // list of 12 float values for each month
}
"""
# Initialize the class with all data missing
stat_ob = cls(None)
# Check required and optional keys
option_keys_none = ('ashrae_climate_zone', 'koppen_climate_zone',
'extreme_cold_week', 'extreme_hot_week',
'standard_pressure_at_elev')
option_keys_list = ('monthly_db_50', 'monthly_wb_50',
'monthly_db_range_50', 'monthly_wb_range_50',
'monthly_db_100', 'monthly_wb_100', 'monthly_db_20',
'monthly_wb_20', 'monthly_db_04', 'monthly_wb_04',
'monthly_wind', 'monthly_wind_dirs',
'monthly_tau_beam', 'monthly_tau_diffuse')
option_keys_dict = ('typical_weeks', 'heating_dict', 'cooling_dict')
assert 'location' in data, 'Required key "location" is missing!'
for key in option_keys_none:
if key not in data:
data[key] = None
for key in option_keys_list:
if key not in data:
data[key] = []
for key in option_keys_dict:
if key not in data:
data[key] = {}
# assign the properties of the dictionary to the stat object.
stat_ob._location = Location.from_json(data['location'])
stat_ob._ashrae_climate_zone = data['ashrae_climate_zone']
stat_ob._koppen_climate_zone = data['koppen_climate_zone']
stat_ob._extreme_cold_week = AnalysisPeriod.from_json(data['extreme_cold_week'])\
if data['extreme_cold_week'] else None
stat_ob._extreme_hot_week = AnalysisPeriod.from_json(data['extreme_hot_week'])\
if data['extreme_hot_week'] else None
stat_ob._typical_weeks = {}
for key, val in data['typical_weeks'].items():
if isinstance(val, list):
stat_ob._typical_weeks[key] = [AnalysisPeriod.from_json(v) for v in val]
else:
stat_ob._typical_weeks[key] = AnalysisPeriod.from_json(val)
stat_ob._winter_des_day_dict = data['heating_dict']
stat_ob._summer_des_day_dict = data['cooling_dict']
stat_ob._monthly_db_50 = data['monthly_db_50']
stat_ob._monthly_wb_50 = data['monthly_wb_50']
stat_ob._monthly_db_range_50 = data['monthly_db_range_50']
stat_ob._monthly_wb_range_50 = data['monthly_wb_range_50']
stat_ob._monthly_db_100 = data['monthly_db_100']
stat_ob._monthly_wb_100 = data['monthly_wb_100']
stat_ob._monthly_db_20 = data['monthly_db_20']
stat_ob._monthly_wb_20 = data['monthly_wb_20']
stat_ob._monthly_db_04 = data['monthly_db_04']
stat_ob._monthly_wb_04 = data['monthly_wb_04']
stat_ob._monthly_wind = data['monthly_wind']
stat_ob._monthly_wind_dirs = data['monthly_wind_dirs']
stat_ob._stand_press_at_elev = data['standard_pressure_at_elev']
stat_ob._monthly_tau_beam = data['monthly_tau_beam']
stat_ob._monthly_tau_diffuse = data['monthly_tau_diffuse']
return stat_ob | [
"def",
"from_json",
"(",
"cls",
",",
"data",
")",
":",
"# Initialize the class with all data missing",
"stat_ob",
"=",
"cls",
"(",
"None",
")",
"# Check required and optional keys",
"option_keys_none",
"=",
"(",
"'ashrae_climate_zone'",
",",
"'koppen_climate_zone'",
",",
"'extreme_cold_week'",
",",
"'extreme_hot_week'",
",",
"'standard_pressure_at_elev'",
")",
"option_keys_list",
"=",
"(",
"'monthly_db_50'",
",",
"'monthly_wb_50'",
",",
"'monthly_db_range_50'",
",",
"'monthly_wb_range_50'",
",",
"'monthly_db_100'",
",",
"'monthly_wb_100'",
",",
"'monthly_db_20'",
",",
"'monthly_wb_20'",
",",
"'monthly_db_04'",
",",
"'monthly_wb_04'",
",",
"'monthly_wind'",
",",
"'monthly_wind_dirs'",
",",
"'monthly_tau_beam'",
",",
"'monthly_tau_diffuse'",
")",
"option_keys_dict",
"=",
"(",
"'typical_weeks'",
",",
"'heating_dict'",
",",
"'cooling_dict'",
")",
"assert",
"'location'",
"in",
"data",
",",
"'Required key \"location\" is missing!'",
"for",
"key",
"in",
"option_keys_none",
":",
"if",
"key",
"not",
"in",
"data",
":",
"data",
"[",
"key",
"]",
"=",
"None",
"for",
"key",
"in",
"option_keys_list",
":",
"if",
"key",
"not",
"in",
"data",
":",
"data",
"[",
"key",
"]",
"=",
"[",
"]",
"for",
"key",
"in",
"option_keys_dict",
":",
"if",
"key",
"not",
"in",
"data",
":",
"data",
"[",
"key",
"]",
"=",
"{",
"}",
"# assign the properties of the dictionary to the stat object.",
"stat_ob",
".",
"_location",
"=",
"Location",
".",
"from_json",
"(",
"data",
"[",
"'location'",
"]",
")",
"stat_ob",
".",
"_ashrae_climate_zone",
"=",
"data",
"[",
"'ashrae_climate_zone'",
"]",
"stat_ob",
".",
"_koppen_climate_zone",
"=",
"data",
"[",
"'koppen_climate_zone'",
"]",
"stat_ob",
".",
"_extreme_cold_week",
"=",
"AnalysisPeriod",
".",
"from_json",
"(",
"data",
"[",
"'extreme_cold_week'",
"]",
")",
"if",
"data",
"[",
"'extreme_cold_week'",
"]",
"else",
"None",
"stat_ob",
".",
"_extreme_hot_week",
"=",
"AnalysisPeriod",
".",
"from_json",
"(",
"data",
"[",
"'extreme_hot_week'",
"]",
")",
"if",
"data",
"[",
"'extreme_hot_week'",
"]",
"else",
"None",
"stat_ob",
".",
"_typical_weeks",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"data",
"[",
"'typical_weeks'",
"]",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"stat_ob",
".",
"_typical_weeks",
"[",
"key",
"]",
"=",
"[",
"AnalysisPeriod",
".",
"from_json",
"(",
"v",
")",
"for",
"v",
"in",
"val",
"]",
"else",
":",
"stat_ob",
".",
"_typical_weeks",
"[",
"key",
"]",
"=",
"AnalysisPeriod",
".",
"from_json",
"(",
"val",
")",
"stat_ob",
".",
"_winter_des_day_dict",
"=",
"data",
"[",
"'heating_dict'",
"]",
"stat_ob",
".",
"_summer_des_day_dict",
"=",
"data",
"[",
"'cooling_dict'",
"]",
"stat_ob",
".",
"_monthly_db_50",
"=",
"data",
"[",
"'monthly_db_50'",
"]",
"stat_ob",
".",
"_monthly_wb_50",
"=",
"data",
"[",
"'monthly_wb_50'",
"]",
"stat_ob",
".",
"_monthly_db_range_50",
"=",
"data",
"[",
"'monthly_db_range_50'",
"]",
"stat_ob",
".",
"_monthly_wb_range_50",
"=",
"data",
"[",
"'monthly_wb_range_50'",
"]",
"stat_ob",
".",
"_monthly_db_100",
"=",
"data",
"[",
"'monthly_db_100'",
"]",
"stat_ob",
".",
"_monthly_wb_100",
"=",
"data",
"[",
"'monthly_wb_100'",
"]",
"stat_ob",
".",
"_monthly_db_20",
"=",
"data",
"[",
"'monthly_db_20'",
"]",
"stat_ob",
".",
"_monthly_wb_20",
"=",
"data",
"[",
"'monthly_wb_20'",
"]",
"stat_ob",
".",
"_monthly_db_04",
"=",
"data",
"[",
"'monthly_db_04'",
"]",
"stat_ob",
".",
"_monthly_wb_04",
"=",
"data",
"[",
"'monthly_wb_04'",
"]",
"stat_ob",
".",
"_monthly_wind",
"=",
"data",
"[",
"'monthly_wind'",
"]",
"stat_ob",
".",
"_monthly_wind_dirs",
"=",
"data",
"[",
"'monthly_wind_dirs'",
"]",
"stat_ob",
".",
"_stand_press_at_elev",
"=",
"data",
"[",
"'standard_pressure_at_elev'",
"]",
"stat_ob",
".",
"_monthly_tau_beam",
"=",
"data",
"[",
"'monthly_tau_beam'",
"]",
"stat_ob",
".",
"_monthly_tau_diffuse",
"=",
"data",
"[",
"'monthly_tau_diffuse'",
"]",
"return",
"stat_ob"
] | Create STAT from json dictionary.
Args:
data: {
'location': {} , // ladybug location schema
'ashrae_climate_zone': str,
'koppen_climate_zone': str,
'extreme_cold_week': {}, // ladybug analysis period schema
'extreme_hot_week': {}, // ladybug analysis period schema
'typical_weeks': {}, // dict of ladybug analysis period schemas
'heating_dict': {}, // dict containing heating design conditions
'cooling_dict': {}, // dict containing cooling design conditions
"monthly_db_50": [], // list of 12 float values for each month
"monthly_wb_50": [], // list of 12 float values for each month
"monthly_db_range_50": [], // list of 12 float values for each month
"monthly_wb_range_50": [], // list of 12 float values for each month
"monthly_db_100": [], // list of 12 float values for each month
"monthly_wb_100": [], // list of 12 float values for each month
"monthly_db_20": [], // list of 12 float values for each month
"monthly_wb_20": [], // list of 12 float values for each month
"monthly_db_04": [], // list of 12 float values for each month
"monthly_wb_04": [], // list of 12 float values for each month
"monthly_wind": [], // list of 12 float values for each month
"monthly_wind_dirs": [], // matrix with 12 cols for months of the year
and 8 rows for the cardinal directions.
"standard_pressure_at_elev": float, // float value for pressure in Pa
"monthly_tau_beam":[], // list of 12 float values for each month
"monthly_tau_diffuse": [] // list of 12 float values for each month
} | [
"Create",
"STAT",
"from",
"json",
"dictionary",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/stat.py#L87-L175 | train | 237,431 |
ladybug-tools/ladybug | ladybug/stat.py | STAT.monthly_cooling_design_days_050 | def monthly_cooling_design_days_050(self):
"""A list of 12 objects representing monthly 5.0% cooling design days."""
if self.monthly_found is False or self._monthly_db_50 == [] \
or self._monthly_wb_50 == []:
return []
else:
db_conds = [DryBulbCondition(x, y) for x, y in zip(
self._monthly_db_50, self._monthly_db_range_50)]
hu_conds = [HumidityCondition(
'Wetbulb', x, self._stand_press_at_elev) for x in self._monthly_wb_50]
ws_conds = self.monthly_wind_conditions
sky_conds = self.monthly_clear_sky_conditions
return [DesignDay(
'5% Cooling Design Day for {}'.format(self._months[i]),
'SummerDesignDay', self._location,
db_conds[i], hu_conds[i], ws_conds[i], sky_conds[i])
for i in xrange(12)] | python | def monthly_cooling_design_days_050(self):
"""A list of 12 objects representing monthly 5.0% cooling design days."""
if self.monthly_found is False or self._monthly_db_50 == [] \
or self._monthly_wb_50 == []:
return []
else:
db_conds = [DryBulbCondition(x, y) for x, y in zip(
self._monthly_db_50, self._monthly_db_range_50)]
hu_conds = [HumidityCondition(
'Wetbulb', x, self._stand_press_at_elev) for x in self._monthly_wb_50]
ws_conds = self.monthly_wind_conditions
sky_conds = self.monthly_clear_sky_conditions
return [DesignDay(
'5% Cooling Design Day for {}'.format(self._months[i]),
'SummerDesignDay', self._location,
db_conds[i], hu_conds[i], ws_conds[i], sky_conds[i])
for i in xrange(12)] | [
"def",
"monthly_cooling_design_days_050",
"(",
"self",
")",
":",
"if",
"self",
".",
"monthly_found",
"is",
"False",
"or",
"self",
".",
"_monthly_db_50",
"==",
"[",
"]",
"or",
"self",
".",
"_monthly_wb_50",
"==",
"[",
"]",
":",
"return",
"[",
"]",
"else",
":",
"db_conds",
"=",
"[",
"DryBulbCondition",
"(",
"x",
",",
"y",
")",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"self",
".",
"_monthly_db_50",
",",
"self",
".",
"_monthly_db_range_50",
")",
"]",
"hu_conds",
"=",
"[",
"HumidityCondition",
"(",
"'Wetbulb'",
",",
"x",
",",
"self",
".",
"_stand_press_at_elev",
")",
"for",
"x",
"in",
"self",
".",
"_monthly_wb_50",
"]",
"ws_conds",
"=",
"self",
".",
"monthly_wind_conditions",
"sky_conds",
"=",
"self",
".",
"monthly_clear_sky_conditions",
"return",
"[",
"DesignDay",
"(",
"'5% Cooling Design Day for {}'",
".",
"format",
"(",
"self",
".",
"_months",
"[",
"i",
"]",
")",
",",
"'SummerDesignDay'",
",",
"self",
".",
"_location",
",",
"db_conds",
"[",
"i",
"]",
",",
"hu_conds",
"[",
"i",
"]",
",",
"ws_conds",
"[",
"i",
"]",
",",
"sky_conds",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"xrange",
"(",
"12",
")",
"]"
] | A list of 12 objects representing monthly 5.0% cooling design days. | [
"A",
"list",
"of",
"12",
"objects",
"representing",
"monthly",
"5",
".",
"0%",
"cooling",
"design",
"days",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/stat.py#L497-L513 | train | 237,432 |
ladybug-tools/ladybug | ladybug/stat.py | STAT.monthly_cooling_design_days_100 | def monthly_cooling_design_days_100(self):
"""A list of 12 objects representing monthly 10.0% cooling design days."""
if self.monthly_found is False or self._monthly_db_100 == [] \
or self._monthly_wb_100 == []:
return []
else:
db_conds = [DryBulbCondition(x, y) for x, y in zip(
self._monthly_db_100, self._monthly_db_range_50)]
hu_conds = [HumidityCondition(
'Wetbulb', x, self._stand_press_at_elev) for x in self._monthly_wb_100]
ws_conds = self.monthly_wind_conditions
sky_conds = self.monthly_clear_sky_conditions
return [DesignDay(
'10% Cooling Design Day for {}'.format(self._months[i]),
'SummerDesignDay', self._location,
db_conds[i], hu_conds[i], ws_conds[i], sky_conds[i])
for i in xrange(12)] | python | def monthly_cooling_design_days_100(self):
"""A list of 12 objects representing monthly 10.0% cooling design days."""
if self.monthly_found is False or self._monthly_db_100 == [] \
or self._monthly_wb_100 == []:
return []
else:
db_conds = [DryBulbCondition(x, y) for x, y in zip(
self._monthly_db_100, self._monthly_db_range_50)]
hu_conds = [HumidityCondition(
'Wetbulb', x, self._stand_press_at_elev) for x in self._monthly_wb_100]
ws_conds = self.monthly_wind_conditions
sky_conds = self.monthly_clear_sky_conditions
return [DesignDay(
'10% Cooling Design Day for {}'.format(self._months[i]),
'SummerDesignDay', self._location,
db_conds[i], hu_conds[i], ws_conds[i], sky_conds[i])
for i in xrange(12)] | [
"def",
"monthly_cooling_design_days_100",
"(",
"self",
")",
":",
"if",
"self",
".",
"monthly_found",
"is",
"False",
"or",
"self",
".",
"_monthly_db_100",
"==",
"[",
"]",
"or",
"self",
".",
"_monthly_wb_100",
"==",
"[",
"]",
":",
"return",
"[",
"]",
"else",
":",
"db_conds",
"=",
"[",
"DryBulbCondition",
"(",
"x",
",",
"y",
")",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"self",
".",
"_monthly_db_100",
",",
"self",
".",
"_monthly_db_range_50",
")",
"]",
"hu_conds",
"=",
"[",
"HumidityCondition",
"(",
"'Wetbulb'",
",",
"x",
",",
"self",
".",
"_stand_press_at_elev",
")",
"for",
"x",
"in",
"self",
".",
"_monthly_wb_100",
"]",
"ws_conds",
"=",
"self",
".",
"monthly_wind_conditions",
"sky_conds",
"=",
"self",
".",
"monthly_clear_sky_conditions",
"return",
"[",
"DesignDay",
"(",
"'10% Cooling Design Day for {}'",
".",
"format",
"(",
"self",
".",
"_months",
"[",
"i",
"]",
")",
",",
"'SummerDesignDay'",
",",
"self",
".",
"_location",
",",
"db_conds",
"[",
"i",
"]",
",",
"hu_conds",
"[",
"i",
"]",
",",
"ws_conds",
"[",
"i",
"]",
",",
"sky_conds",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"xrange",
"(",
"12",
")",
"]"
] | A list of 12 objects representing monthly 10.0% cooling design days. | [
"A",
"list",
"of",
"12",
"objects",
"representing",
"monthly",
"10",
".",
"0%",
"cooling",
"design",
"days",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/stat.py#L516-L532 | train | 237,433 |
ladybug-tools/ladybug | ladybug/stat.py | STAT.monthly_cooling_design_days_020 | def monthly_cooling_design_days_020(self):
"""A list of 12 objects representing monthly 2.0% cooling design days."""
if self.monthly_found is False or self._monthly_db_20 == [] \
or self._monthly_wb_20 == []:
return []
else:
db_conds = [DryBulbCondition(x, y) for x, y in zip(
self._monthly_db_20, self._monthly_db_range_50)]
hu_conds = [HumidityCondition(
'Wetbulb', x, self._stand_press_at_elev) for x in self._monthly_wb_20]
ws_conds = self.monthly_wind_conditions
sky_conds = self.monthly_clear_sky_conditions
return [DesignDay(
'2% Cooling Design Day for {}'.format(self._months[i]),
'SummerDesignDay', self._location,
db_conds[i], hu_conds[i], ws_conds[i], sky_conds[i])
for i in xrange(12)] | python | def monthly_cooling_design_days_020(self):
"""A list of 12 objects representing monthly 2.0% cooling design days."""
if self.monthly_found is False or self._monthly_db_20 == [] \
or self._monthly_wb_20 == []:
return []
else:
db_conds = [DryBulbCondition(x, y) for x, y in zip(
self._monthly_db_20, self._monthly_db_range_50)]
hu_conds = [HumidityCondition(
'Wetbulb', x, self._stand_press_at_elev) for x in self._monthly_wb_20]
ws_conds = self.monthly_wind_conditions
sky_conds = self.monthly_clear_sky_conditions
return [DesignDay(
'2% Cooling Design Day for {}'.format(self._months[i]),
'SummerDesignDay', self._location,
db_conds[i], hu_conds[i], ws_conds[i], sky_conds[i])
for i in xrange(12)] | [
"def",
"monthly_cooling_design_days_020",
"(",
"self",
")",
":",
"if",
"self",
".",
"monthly_found",
"is",
"False",
"or",
"self",
".",
"_monthly_db_20",
"==",
"[",
"]",
"or",
"self",
".",
"_monthly_wb_20",
"==",
"[",
"]",
":",
"return",
"[",
"]",
"else",
":",
"db_conds",
"=",
"[",
"DryBulbCondition",
"(",
"x",
",",
"y",
")",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"self",
".",
"_monthly_db_20",
",",
"self",
".",
"_monthly_db_range_50",
")",
"]",
"hu_conds",
"=",
"[",
"HumidityCondition",
"(",
"'Wetbulb'",
",",
"x",
",",
"self",
".",
"_stand_press_at_elev",
")",
"for",
"x",
"in",
"self",
".",
"_monthly_wb_20",
"]",
"ws_conds",
"=",
"self",
".",
"monthly_wind_conditions",
"sky_conds",
"=",
"self",
".",
"monthly_clear_sky_conditions",
"return",
"[",
"DesignDay",
"(",
"'2% Cooling Design Day for {}'",
".",
"format",
"(",
"self",
".",
"_months",
"[",
"i",
"]",
")",
",",
"'SummerDesignDay'",
",",
"self",
".",
"_location",
",",
"db_conds",
"[",
"i",
"]",
",",
"hu_conds",
"[",
"i",
"]",
",",
"ws_conds",
"[",
"i",
"]",
",",
"sky_conds",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"xrange",
"(",
"12",
")",
"]"
] | A list of 12 objects representing monthly 2.0% cooling design days. | [
"A",
"list",
"of",
"12",
"objects",
"representing",
"monthly",
"2",
".",
"0%",
"cooling",
"design",
"days",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/stat.py#L535-L551 | train | 237,434 |
ladybug-tools/ladybug | ladybug/stat.py | STAT.monthly_cooling_design_days_004 | def monthly_cooling_design_days_004(self):
"""A list of 12 objects representing monthly 0.4% cooling design days."""
if self.monthly_found is False or self._monthly_db_04 == [] \
or self._monthly_wb_04 == []:
return []
else:
db_conds = [DryBulbCondition(x, y) for x, y in zip(
self._monthly_db_04, self._monthly_db_range_50)]
hu_conds = [HumidityCondition(
'Wetbulb', x, self._stand_press_at_elev) for x in self._monthly_wb_04]
ws_conds = self.monthly_wind_conditions
sky_conds = self.monthly_clear_sky_conditions
return [DesignDay(
'0.4% Cooling Design Day for {}'.format(self._months[i]),
'SummerDesignDay', self._location,
db_conds[i], hu_conds[i], ws_conds[i], sky_conds[i])
for i in xrange(12)] | python | def monthly_cooling_design_days_004(self):
"""A list of 12 objects representing monthly 0.4% cooling design days."""
if self.monthly_found is False or self._monthly_db_04 == [] \
or self._monthly_wb_04 == []:
return []
else:
db_conds = [DryBulbCondition(x, y) for x, y in zip(
self._monthly_db_04, self._monthly_db_range_50)]
hu_conds = [HumidityCondition(
'Wetbulb', x, self._stand_press_at_elev) for x in self._monthly_wb_04]
ws_conds = self.monthly_wind_conditions
sky_conds = self.monthly_clear_sky_conditions
return [DesignDay(
'0.4% Cooling Design Day for {}'.format(self._months[i]),
'SummerDesignDay', self._location,
db_conds[i], hu_conds[i], ws_conds[i], sky_conds[i])
for i in xrange(12)] | [
"def",
"monthly_cooling_design_days_004",
"(",
"self",
")",
":",
"if",
"self",
".",
"monthly_found",
"is",
"False",
"or",
"self",
".",
"_monthly_db_04",
"==",
"[",
"]",
"or",
"self",
".",
"_monthly_wb_04",
"==",
"[",
"]",
":",
"return",
"[",
"]",
"else",
":",
"db_conds",
"=",
"[",
"DryBulbCondition",
"(",
"x",
",",
"y",
")",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"self",
".",
"_monthly_db_04",
",",
"self",
".",
"_monthly_db_range_50",
")",
"]",
"hu_conds",
"=",
"[",
"HumidityCondition",
"(",
"'Wetbulb'",
",",
"x",
",",
"self",
".",
"_stand_press_at_elev",
")",
"for",
"x",
"in",
"self",
".",
"_monthly_wb_04",
"]",
"ws_conds",
"=",
"self",
".",
"monthly_wind_conditions",
"sky_conds",
"=",
"self",
".",
"monthly_clear_sky_conditions",
"return",
"[",
"DesignDay",
"(",
"'0.4% Cooling Design Day for {}'",
".",
"format",
"(",
"self",
".",
"_months",
"[",
"i",
"]",
")",
",",
"'SummerDesignDay'",
",",
"self",
".",
"_location",
",",
"db_conds",
"[",
"i",
"]",
",",
"hu_conds",
"[",
"i",
"]",
",",
"ws_conds",
"[",
"i",
"]",
",",
"sky_conds",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"xrange",
"(",
"12",
")",
"]"
] | A list of 12 objects representing monthly 0.4% cooling design days. | [
"A",
"list",
"of",
"12",
"objects",
"representing",
"monthly",
"0",
".",
"4%",
"cooling",
"design",
"days",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/stat.py#L554-L570 | train | 237,435 |
ladybug-tools/ladybug | ladybug/stat.py | STAT.monthly_wind_conditions | def monthly_wind_conditions(self):
"""A list of 12 monthly wind conditions that are used on the design days."""
return [WindCondition(x, y) for x, y in zip(
self._monthly_wind, self.monthly_wind_dirs)] | python | def monthly_wind_conditions(self):
"""A list of 12 monthly wind conditions that are used on the design days."""
return [WindCondition(x, y) for x, y in zip(
self._monthly_wind, self.monthly_wind_dirs)] | [
"def",
"monthly_wind_conditions",
"(",
"self",
")",
":",
"return",
"[",
"WindCondition",
"(",
"x",
",",
"y",
")",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"self",
".",
"_monthly_wind",
",",
"self",
".",
"monthly_wind_dirs",
")",
"]"
] | A list of 12 monthly wind conditions that are used on the design days. | [
"A",
"list",
"of",
"12",
"monthly",
"wind",
"conditions",
"that",
"are",
"used",
"on",
"the",
"design",
"days",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/stat.py#L598-L601 | train | 237,436 |
ladybug-tools/ladybug | ladybug/stat.py | STAT.monthly_wind_dirs | def monthly_wind_dirs(self):
"""A list of prevailing wind directions for each month."""
mwd = zip(*self._monthly_wind_dirs)
return [self._wind_dirs[mon.index(max(mon))] for mon in mwd] | python | def monthly_wind_dirs(self):
"""A list of prevailing wind directions for each month."""
mwd = zip(*self._monthly_wind_dirs)
return [self._wind_dirs[mon.index(max(mon))] for mon in mwd] | [
"def",
"monthly_wind_dirs",
"(",
"self",
")",
":",
"mwd",
"=",
"zip",
"(",
"*",
"self",
".",
"_monthly_wind_dirs",
")",
"return",
"[",
"self",
".",
"_wind_dirs",
"[",
"mon",
".",
"index",
"(",
"max",
"(",
"mon",
")",
")",
"]",
"for",
"mon",
"in",
"mwd",
"]"
] | A list of prevailing wind directions for each month. | [
"A",
"list",
"of",
"prevailing",
"wind",
"directions",
"for",
"each",
"month",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/stat.py#L609-L612 | train | 237,437 |
ladybug-tools/ladybug | ladybug/stat.py | STAT.monthly_clear_sky_conditions | def monthly_clear_sky_conditions(self):
"""A list of 12 monthly clear sky conditions that are used on the design days."""
if self._monthly_tau_diffuse is [] or self._monthly_tau_beam is []:
return [OriginalClearSkyCondition(i, 21) for i in xrange(1, 13)]
return [RevisedClearSkyCondition(i, 21, x, y) for i, x, y in zip(
list(xrange(1, 13)), self._monthly_tau_beam, self._monthly_tau_diffuse)] | python | def monthly_clear_sky_conditions(self):
"""A list of 12 monthly clear sky conditions that are used on the design days."""
if self._monthly_tau_diffuse is [] or self._monthly_tau_beam is []:
return [OriginalClearSkyCondition(i, 21) for i in xrange(1, 13)]
return [RevisedClearSkyCondition(i, 21, x, y) for i, x, y in zip(
list(xrange(1, 13)), self._monthly_tau_beam, self._monthly_tau_diffuse)] | [
"def",
"monthly_clear_sky_conditions",
"(",
"self",
")",
":",
"if",
"self",
".",
"_monthly_tau_diffuse",
"is",
"[",
"]",
"or",
"self",
".",
"_monthly_tau_beam",
"is",
"[",
"]",
":",
"return",
"[",
"OriginalClearSkyCondition",
"(",
"i",
",",
"21",
")",
"for",
"i",
"in",
"xrange",
"(",
"1",
",",
"13",
")",
"]",
"return",
"[",
"RevisedClearSkyCondition",
"(",
"i",
",",
"21",
",",
"x",
",",
"y",
")",
"for",
"i",
",",
"x",
",",
"y",
"in",
"zip",
"(",
"list",
"(",
"xrange",
"(",
"1",
",",
"13",
")",
")",
",",
"self",
".",
"_monthly_tau_beam",
",",
"self",
".",
"_monthly_tau_diffuse",
")",
"]"
] | A list of 12 monthly clear sky conditions that are used on the design days. | [
"A",
"list",
"of",
"12",
"monthly",
"clear",
"sky",
"conditions",
"that",
"are",
"used",
"on",
"the",
"design",
"days",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/stat.py#L615-L620 | train | 237,438 |
ladybug-tools/ladybug | ladybug/stat.py | STAT.to_json | def to_json(self):
"""Convert the STAT object to a dictionary."""
def jsonify_dict(base_dict):
new_dict = {}
for key, val in base_dict.items():
if isinstance(val, list):
new_dict[key] = [v.to_json() for v in val]
else:
new_dict[key] = val.to_json()
return new_dict
return {
'location': self.location.to_json(),
'ashrae_climate_zone': self.ashrae_climate_zone,
'koppen_climate_zone': self.koppen_climate_zone,
'extreme_cold_week': self.extreme_cold_week.to_json()
if self.extreme_cold_week else None,
'extreme_hot_week': self.extreme_hot_week.to_json()
if self.extreme_cold_week else None,
'typical_weeks': jsonify_dict(self._typical_weeks),
'heating_dict': self._winter_des_day_dict,
'cooling_dict': self._summer_des_day_dict,
"monthly_db_50": self._monthly_db_50,
"monthly_wb_50": self._monthly_wb_50,
"monthly_db_range_50": self._monthly_db_range_50,
"monthly_wb_range_50": self._monthly_wb_range_50,
"monthly_db_100": self._monthly_db_100,
"monthly_wb_100": self._monthly_wb_100,
"monthly_db_20": self._monthly_db_20,
"monthly_wb_20": self._monthly_wb_20,
"monthly_db_04": self._monthly_db_04,
"monthly_wb_04": self._monthly_wb_04,
"monthly_wind": self._monthly_wind,
"monthly_wind_dirs": self._monthly_wind_dirs,
"standard_pressure_at_elev": self.standard_pressure_at_elev,
"monthly_tau_beam": self.monthly_tau_beam,
"monthly_tau_diffuse": self.monthly_tau_diffuse
} | python | def to_json(self):
"""Convert the STAT object to a dictionary."""
def jsonify_dict(base_dict):
new_dict = {}
for key, val in base_dict.items():
if isinstance(val, list):
new_dict[key] = [v.to_json() for v in val]
else:
new_dict[key] = val.to_json()
return new_dict
return {
'location': self.location.to_json(),
'ashrae_climate_zone': self.ashrae_climate_zone,
'koppen_climate_zone': self.koppen_climate_zone,
'extreme_cold_week': self.extreme_cold_week.to_json()
if self.extreme_cold_week else None,
'extreme_hot_week': self.extreme_hot_week.to_json()
if self.extreme_cold_week else None,
'typical_weeks': jsonify_dict(self._typical_weeks),
'heating_dict': self._winter_des_day_dict,
'cooling_dict': self._summer_des_day_dict,
"monthly_db_50": self._monthly_db_50,
"monthly_wb_50": self._monthly_wb_50,
"monthly_db_range_50": self._monthly_db_range_50,
"monthly_wb_range_50": self._monthly_wb_range_50,
"monthly_db_100": self._monthly_db_100,
"monthly_wb_100": self._monthly_wb_100,
"monthly_db_20": self._monthly_db_20,
"monthly_wb_20": self._monthly_wb_20,
"monthly_db_04": self._monthly_db_04,
"monthly_wb_04": self._monthly_wb_04,
"monthly_wind": self._monthly_wind,
"monthly_wind_dirs": self._monthly_wind_dirs,
"standard_pressure_at_elev": self.standard_pressure_at_elev,
"monthly_tau_beam": self.monthly_tau_beam,
"monthly_tau_diffuse": self.monthly_tau_diffuse
} | [
"def",
"to_json",
"(",
"self",
")",
":",
"def",
"jsonify_dict",
"(",
"base_dict",
")",
":",
"new_dict",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"base_dict",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"new_dict",
"[",
"key",
"]",
"=",
"[",
"v",
".",
"to_json",
"(",
")",
"for",
"v",
"in",
"val",
"]",
"else",
":",
"new_dict",
"[",
"key",
"]",
"=",
"val",
".",
"to_json",
"(",
")",
"return",
"new_dict",
"return",
"{",
"'location'",
":",
"self",
".",
"location",
".",
"to_json",
"(",
")",
",",
"'ashrae_climate_zone'",
":",
"self",
".",
"ashrae_climate_zone",
",",
"'koppen_climate_zone'",
":",
"self",
".",
"koppen_climate_zone",
",",
"'extreme_cold_week'",
":",
"self",
".",
"extreme_cold_week",
".",
"to_json",
"(",
")",
"if",
"self",
".",
"extreme_cold_week",
"else",
"None",
",",
"'extreme_hot_week'",
":",
"self",
".",
"extreme_hot_week",
".",
"to_json",
"(",
")",
"if",
"self",
".",
"extreme_cold_week",
"else",
"None",
",",
"'typical_weeks'",
":",
"jsonify_dict",
"(",
"self",
".",
"_typical_weeks",
")",
",",
"'heating_dict'",
":",
"self",
".",
"_winter_des_day_dict",
",",
"'cooling_dict'",
":",
"self",
".",
"_summer_des_day_dict",
",",
"\"monthly_db_50\"",
":",
"self",
".",
"_monthly_db_50",
",",
"\"monthly_wb_50\"",
":",
"self",
".",
"_monthly_wb_50",
",",
"\"monthly_db_range_50\"",
":",
"self",
".",
"_monthly_db_range_50",
",",
"\"monthly_wb_range_50\"",
":",
"self",
".",
"_monthly_wb_range_50",
",",
"\"monthly_db_100\"",
":",
"self",
".",
"_monthly_db_100",
",",
"\"monthly_wb_100\"",
":",
"self",
".",
"_monthly_wb_100",
",",
"\"monthly_db_20\"",
":",
"self",
".",
"_monthly_db_20",
",",
"\"monthly_wb_20\"",
":",
"self",
".",
"_monthly_wb_20",
",",
"\"monthly_db_04\"",
":",
"self",
".",
"_monthly_db_04",
",",
"\"monthly_wb_04\"",
":",
"self",
".",
"_monthly_wb_04",
",",
"\"monthly_wind\"",
":",
"self",
".",
"_monthly_wind",
",",
"\"monthly_wind_dirs\"",
":",
"self",
".",
"_monthly_wind_dirs",
",",
"\"standard_pressure_at_elev\"",
":",
"self",
".",
"standard_pressure_at_elev",
",",
"\"monthly_tau_beam\"",
":",
"self",
".",
"monthly_tau_beam",
",",
"\"monthly_tau_diffuse\"",
":",
"self",
".",
"monthly_tau_diffuse",
"}"
] | Convert the STAT object to a dictionary. | [
"Convert",
"the",
"STAT",
"object",
"to",
"a",
"dictionary",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/stat.py#L642-L678 | train | 237,439 |
ladybug-tools/ladybug | ladybug/datatype/base.py | DataTypeBase.from_json | def from_json(cls, data):
"""Create a data type from a dictionary.
Args:
data: Data as a dictionary.
{
"name": data type name of the data type as a string
"data_type": the class name of the data type as a string
"base_unit": the base unit of the data type
}
"""
assert 'name' in data, 'Required keyword "name" is missing!'
assert 'data_type' in data, 'Required keyword "data_type" is missing!'
if cls._type_enumeration is None:
cls._type_enumeration = _DataTypeEnumeration(import_modules=False)
if data['data_type'] == 'GenericType':
assert 'base_unit' in data, \
'Keyword "base_unit" is missing and is required for GenericType.'
return cls._type_enumeration._GENERICTYPE(data['name'], data['base_unit'])
elif data['data_type'] in cls._type_enumeration._TYPES:
clss = cls._type_enumeration._TYPES[data['data_type']]
if data['data_type'] == data['name'].title().replace(' ', ''):
return clss()
else:
instance = clss()
instance._name = data['name']
return instance
else:
raise ValueError(
'Data Type {} could not be recognized'.format(data['data_type'])) | python | def from_json(cls, data):
"""Create a data type from a dictionary.
Args:
data: Data as a dictionary.
{
"name": data type name of the data type as a string
"data_type": the class name of the data type as a string
"base_unit": the base unit of the data type
}
"""
assert 'name' in data, 'Required keyword "name" is missing!'
assert 'data_type' in data, 'Required keyword "data_type" is missing!'
if cls._type_enumeration is None:
cls._type_enumeration = _DataTypeEnumeration(import_modules=False)
if data['data_type'] == 'GenericType':
assert 'base_unit' in data, \
'Keyword "base_unit" is missing and is required for GenericType.'
return cls._type_enumeration._GENERICTYPE(data['name'], data['base_unit'])
elif data['data_type'] in cls._type_enumeration._TYPES:
clss = cls._type_enumeration._TYPES[data['data_type']]
if data['data_type'] == data['name'].title().replace(' ', ''):
return clss()
else:
instance = clss()
instance._name = data['name']
return instance
else:
raise ValueError(
'Data Type {} could not be recognized'.format(data['data_type'])) | [
"def",
"from_json",
"(",
"cls",
",",
"data",
")",
":",
"assert",
"'name'",
"in",
"data",
",",
"'Required keyword \"name\" is missing!'",
"assert",
"'data_type'",
"in",
"data",
",",
"'Required keyword \"data_type\" is missing!'",
"if",
"cls",
".",
"_type_enumeration",
"is",
"None",
":",
"cls",
".",
"_type_enumeration",
"=",
"_DataTypeEnumeration",
"(",
"import_modules",
"=",
"False",
")",
"if",
"data",
"[",
"'data_type'",
"]",
"==",
"'GenericType'",
":",
"assert",
"'base_unit'",
"in",
"data",
",",
"'Keyword \"base_unit\" is missing and is required for GenericType.'",
"return",
"cls",
".",
"_type_enumeration",
".",
"_GENERICTYPE",
"(",
"data",
"[",
"'name'",
"]",
",",
"data",
"[",
"'base_unit'",
"]",
")",
"elif",
"data",
"[",
"'data_type'",
"]",
"in",
"cls",
".",
"_type_enumeration",
".",
"_TYPES",
":",
"clss",
"=",
"cls",
".",
"_type_enumeration",
".",
"_TYPES",
"[",
"data",
"[",
"'data_type'",
"]",
"]",
"if",
"data",
"[",
"'data_type'",
"]",
"==",
"data",
"[",
"'name'",
"]",
".",
"title",
"(",
")",
".",
"replace",
"(",
"' '",
",",
"''",
")",
":",
"return",
"clss",
"(",
")",
"else",
":",
"instance",
"=",
"clss",
"(",
")",
"instance",
".",
"_name",
"=",
"data",
"[",
"'name'",
"]",
"return",
"instance",
"else",
":",
"raise",
"ValueError",
"(",
"'Data Type {} could not be recognized'",
".",
"format",
"(",
"data",
"[",
"'data_type'",
"]",
")",
")"
] | Create a data type from a dictionary.
Args:
data: Data as a dictionary.
{
"name": data type name of the data type as a string
"data_type": the class name of the data type as a string
"base_unit": the base unit of the data type
} | [
"Create",
"a",
"data",
"type",
"from",
"a",
"dictionary",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datatype/base.py#L70-L100 | train | 237,440 |
ladybug-tools/ladybug | ladybug/datatype/base.py | DataTypeBase.is_unit_acceptable | def is_unit_acceptable(self, unit, raise_exception=True):
"""Check if a certain unit is acceptable for the data type.
Args:
unit: A text string representing the abbreviated unit.
raise_exception: Set to True to raise an exception if not acceptable.
"""
_is_acceptable = unit in self.units
if _is_acceptable or raise_exception is False:
return _is_acceptable
else:
raise ValueError(
'{0} is not an acceptable unit type for {1}. '
'Choose from the following: {2}'.format(
unit, self.__class__.__name__, self.units
)
) | python | def is_unit_acceptable(self, unit, raise_exception=True):
"""Check if a certain unit is acceptable for the data type.
Args:
unit: A text string representing the abbreviated unit.
raise_exception: Set to True to raise an exception if not acceptable.
"""
_is_acceptable = unit in self.units
if _is_acceptable or raise_exception is False:
return _is_acceptable
else:
raise ValueError(
'{0} is not an acceptable unit type for {1}. '
'Choose from the following: {2}'.format(
unit, self.__class__.__name__, self.units
)
) | [
"def",
"is_unit_acceptable",
"(",
"self",
",",
"unit",
",",
"raise_exception",
"=",
"True",
")",
":",
"_is_acceptable",
"=",
"unit",
"in",
"self",
".",
"units",
"if",
"_is_acceptable",
"or",
"raise_exception",
"is",
"False",
":",
"return",
"_is_acceptable",
"else",
":",
"raise",
"ValueError",
"(",
"'{0} is not an acceptable unit type for {1}. '",
"'Choose from the following: {2}'",
".",
"format",
"(",
"unit",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"units",
")",
")"
] | Check if a certain unit is acceptable for the data type.
Args:
unit: A text string representing the abbreviated unit.
raise_exception: Set to True to raise an exception if not acceptable. | [
"Check",
"if",
"a",
"certain",
"unit",
"is",
"acceptable",
"for",
"the",
"data",
"type",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datatype/base.py#L102-L119 | train | 237,441 |
ladybug-tools/ladybug | ladybug/datatype/base.py | DataTypeBase._is_numeric | def _is_numeric(self, values):
"""Check to be sure values are numbers before doing numerical operations."""
if len(values) > 0:
assert isinstance(values[0], (float, int)), \
"values must be numbers to perform math operations. Got {}".format(
type(values[0]))
return True | python | def _is_numeric(self, values):
"""Check to be sure values are numbers before doing numerical operations."""
if len(values) > 0:
assert isinstance(values[0], (float, int)), \
"values must be numbers to perform math operations. Got {}".format(
type(values[0]))
return True | [
"def",
"_is_numeric",
"(",
"self",
",",
"values",
")",
":",
"if",
"len",
"(",
"values",
")",
">",
"0",
":",
"assert",
"isinstance",
"(",
"values",
"[",
"0",
"]",
",",
"(",
"float",
",",
"int",
")",
")",
",",
"\"values must be numbers to perform math operations. Got {}\"",
".",
"format",
"(",
"type",
"(",
"values",
"[",
"0",
"]",
")",
")",
"return",
"True"
] | Check to be sure values are numbers before doing numerical operations. | [
"Check",
"to",
"be",
"sure",
"values",
"are",
"numbers",
"before",
"doing",
"numerical",
"operations",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datatype/base.py#L188-L194 | train | 237,442 |
ladybug-tools/ladybug | ladybug/datatype/base.py | DataTypeBase._to_unit_base | def _to_unit_base(self, base_unit, values, unit, from_unit):
"""Return values in a given unit given the input from_unit."""
self._is_numeric(values)
namespace = {'self': self, 'values': values}
if not from_unit == base_unit:
self.is_unit_acceptable(from_unit, True)
statement = '[self._{}_to_{}(val) for val in values]'.format(
self._clean(from_unit), self._clean(base_unit))
values = eval(statement, namespace)
namespace['values'] = values
if not unit == base_unit:
self.is_unit_acceptable(unit, True)
statement = '[self._{}_to_{}(val) for val in values]'.format(
self._clean(base_unit), self._clean(unit))
values = eval(statement, namespace)
return values | python | def _to_unit_base(self, base_unit, values, unit, from_unit):
"""Return values in a given unit given the input from_unit."""
self._is_numeric(values)
namespace = {'self': self, 'values': values}
if not from_unit == base_unit:
self.is_unit_acceptable(from_unit, True)
statement = '[self._{}_to_{}(val) for val in values]'.format(
self._clean(from_unit), self._clean(base_unit))
values = eval(statement, namespace)
namespace['values'] = values
if not unit == base_unit:
self.is_unit_acceptable(unit, True)
statement = '[self._{}_to_{}(val) for val in values]'.format(
self._clean(base_unit), self._clean(unit))
values = eval(statement, namespace)
return values | [
"def",
"_to_unit_base",
"(",
"self",
",",
"base_unit",
",",
"values",
",",
"unit",
",",
"from_unit",
")",
":",
"self",
".",
"_is_numeric",
"(",
"values",
")",
"namespace",
"=",
"{",
"'self'",
":",
"self",
",",
"'values'",
":",
"values",
"}",
"if",
"not",
"from_unit",
"==",
"base_unit",
":",
"self",
".",
"is_unit_acceptable",
"(",
"from_unit",
",",
"True",
")",
"statement",
"=",
"'[self._{}_to_{}(val) for val in values]'",
".",
"format",
"(",
"self",
".",
"_clean",
"(",
"from_unit",
")",
",",
"self",
".",
"_clean",
"(",
"base_unit",
")",
")",
"values",
"=",
"eval",
"(",
"statement",
",",
"namespace",
")",
"namespace",
"[",
"'values'",
"]",
"=",
"values",
"if",
"not",
"unit",
"==",
"base_unit",
":",
"self",
".",
"is_unit_acceptable",
"(",
"unit",
",",
"True",
")",
"statement",
"=",
"'[self._{}_to_{}(val) for val in values]'",
".",
"format",
"(",
"self",
".",
"_clean",
"(",
"base_unit",
")",
",",
"self",
".",
"_clean",
"(",
"unit",
")",
")",
"values",
"=",
"eval",
"(",
"statement",
",",
"namespace",
")",
"return",
"values"
] | Return values in a given unit given the input from_unit. | [
"Return",
"values",
"in",
"a",
"given",
"unit",
"given",
"the",
"input",
"from_unit",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datatype/base.py#L196-L211 | train | 237,443 |
ladybug-tools/ladybug | ladybug/datatype/base.py | DataTypeBase.name | def name(self):
"""The data type name."""
if self._name is None:
return re.sub(r"(?<=\w)([A-Z])", r" \1", self.__class__.__name__)
else:
return self._name | python | def name(self):
"""The data type name."""
if self._name is None:
return re.sub(r"(?<=\w)([A-Z])", r" \1", self.__class__.__name__)
else:
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_name",
"is",
"None",
":",
"return",
"re",
".",
"sub",
"(",
"r\"(?<=\\w)([A-Z])\"",
",",
"r\" \\1\"",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
"else",
":",
"return",
"self",
".",
"_name"
] | The data type name. | [
"The",
"data",
"type",
"name",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datatype/base.py#L222-L227 | train | 237,444 |
ladybug-tools/ladybug | ladybug/header.py | Header.from_json | def from_json(cls, data):
"""Create a header from a dictionary.
Args:
data: {
"data_type": {}, //Type of data (e.g. Temperature)
"unit": string,
"analysis_period": {} // A Ladybug AnalysisPeriod
"metadata": {}, // A dictionary of metadata
}
"""
# assign default values
assert 'data_type' in data, 'Required keyword "data_type" is missing!'
keys = ('data_type', 'unit', 'analysis_period', 'metadata')
for key in keys:
if key not in data:
data[key] = None
data_type = DataTypeBase.from_json(data['data_type'])
ap = AnalysisPeriod.from_json(data['analysis_period'])
return cls(data_type, data['unit'], ap, data['metadata']) | python | def from_json(cls, data):
"""Create a header from a dictionary.
Args:
data: {
"data_type": {}, //Type of data (e.g. Temperature)
"unit": string,
"analysis_period": {} // A Ladybug AnalysisPeriod
"metadata": {}, // A dictionary of metadata
}
"""
# assign default values
assert 'data_type' in data, 'Required keyword "data_type" is missing!'
keys = ('data_type', 'unit', 'analysis_period', 'metadata')
for key in keys:
if key not in data:
data[key] = None
data_type = DataTypeBase.from_json(data['data_type'])
ap = AnalysisPeriod.from_json(data['analysis_period'])
return cls(data_type, data['unit'], ap, data['metadata']) | [
"def",
"from_json",
"(",
"cls",
",",
"data",
")",
":",
"# assign default values",
"assert",
"'data_type'",
"in",
"data",
",",
"'Required keyword \"data_type\" is missing!'",
"keys",
"=",
"(",
"'data_type'",
",",
"'unit'",
",",
"'analysis_period'",
",",
"'metadata'",
")",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
"not",
"in",
"data",
":",
"data",
"[",
"key",
"]",
"=",
"None",
"data_type",
"=",
"DataTypeBase",
".",
"from_json",
"(",
"data",
"[",
"'data_type'",
"]",
")",
"ap",
"=",
"AnalysisPeriod",
".",
"from_json",
"(",
"data",
"[",
"'analysis_period'",
"]",
")",
"return",
"cls",
"(",
"data_type",
",",
"data",
"[",
"'unit'",
"]",
",",
"ap",
",",
"data",
"[",
"'metadata'",
"]",
")"
] | Create a header from a dictionary.
Args:
data: {
"data_type": {}, //Type of data (e.g. Temperature)
"unit": string,
"analysis_period": {} // A Ladybug AnalysisPeriod
"metadata": {}, // A dictionary of metadata
} | [
"Create",
"a",
"header",
"from",
"a",
"dictionary",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/header.py#L58-L78 | train | 237,445 |
ladybug-tools/ladybug | ladybug/header.py | Header.duplicate | def duplicate(self):
"""Return a copy of the header."""
a_per = self.analysis_period.duplicate() if self.analysis_period else None
return self.__class__(self.data_type, self.unit,
a_per, deepcopy(self.metadata)) | python | def duplicate(self):
"""Return a copy of the header."""
a_per = self.analysis_period.duplicate() if self.analysis_period else None
return self.__class__(self.data_type, self.unit,
a_per, deepcopy(self.metadata)) | [
"def",
"duplicate",
"(",
"self",
")",
":",
"a_per",
"=",
"self",
".",
"analysis_period",
".",
"duplicate",
"(",
")",
"if",
"self",
".",
"analysis_period",
"else",
"None",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"data_type",
",",
"self",
".",
"unit",
",",
"a_per",
",",
"deepcopy",
"(",
"self",
".",
"metadata",
")",
")"
] | Return a copy of the header. | [
"Return",
"a",
"copy",
"of",
"the",
"header",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/header.py#L105-L109 | train | 237,446 |
ladybug-tools/ladybug | ladybug/header.py | Header.to_tuple | def to_tuple(self):
"""Return Ladybug header as a list."""
return (
self.data_type,
self.unit,
self.analysis_period,
self.metadata
) | python | def to_tuple(self):
"""Return Ladybug header as a list."""
return (
self.data_type,
self.unit,
self.analysis_period,
self.metadata
) | [
"def",
"to_tuple",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"data_type",
",",
"self",
".",
"unit",
",",
"self",
".",
"analysis_period",
",",
"self",
".",
"metadata",
")"
] | Return Ladybug header as a list. | [
"Return",
"Ladybug",
"header",
"as",
"a",
"list",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/header.py#L111-L118 | train | 237,447 |
ladybug-tools/ladybug | ladybug/header.py | Header.to_json | def to_json(self):
"""Return a header as a dictionary."""
a_per = self.analysis_period.to_json() if self.analysis_period else None
return {'data_type': self.data_type.to_json(),
'unit': self.unit,
'analysis_period': a_per,
'metadata': self.metadata} | python | def to_json(self):
"""Return a header as a dictionary."""
a_per = self.analysis_period.to_json() if self.analysis_period else None
return {'data_type': self.data_type.to_json(),
'unit': self.unit,
'analysis_period': a_per,
'metadata': self.metadata} | [
"def",
"to_json",
"(",
"self",
")",
":",
"a_per",
"=",
"self",
".",
"analysis_period",
".",
"to_json",
"(",
")",
"if",
"self",
".",
"analysis_period",
"else",
"None",
"return",
"{",
"'data_type'",
":",
"self",
".",
"data_type",
".",
"to_json",
"(",
")",
",",
"'unit'",
":",
"self",
".",
"unit",
",",
"'analysis_period'",
":",
"a_per",
",",
"'metadata'",
":",
"self",
".",
"metadata",
"}"
] | Return a header as a dictionary. | [
"Return",
"a",
"header",
"as",
"a",
"dictionary",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/header.py#L124-L130 | train | 237,448 |
ladybug-tools/ladybug | ladybug/skymodel.py | ashrae_clear_sky | def ashrae_clear_sky(altitudes, month, sky_clearness=1):
"""Calculate solar flux for an original ASHRAE Clear Sky
Args:
altitudes: A list of solar altitudes in degrees
month: An integer (1-12) indicating the month the altitudes belong to
sky_clearness: A factor that will be multiplied by the output of
the model. This is to help account for locations where clear,
dry skies predominate (e.g., at high elevations) or,
conversely, where hazy and humid conditions are frequent. See
Threlkeld and Jordan (1958) for recommended values. Typical
values range from 0.95 to 1.05 and are usually never more
than 1.2. Default is set to 1.0.
Returns:
dir_norm_rad: A list of direct normal radiation values for each
of the connected altitudes in W/m2.
dif_horiz_rad: A list of diffuse horizontall radiation values for each
of the connected altitudes in W/m2.
"""
# apparent solar irradiation at air mass m = 0
MONTHLY_A = [1202, 1187, 1164, 1130, 1106, 1092, 1093, 1107, 1136,
1166, 1190, 1204]
# atmospheric extinction coefficient
MONTHLY_B = [0.141, 0.142, 0.149, 0.164, 0.177, 0.185, 0.186, 0.182,
0.165, 0.152, 0.144, 0.141]
dir_norm_rad = []
dif_horiz_rad = []
for i, alt in enumerate(altitudes):
if alt > 0:
try:
dir_norm = MONTHLY_A[month - 1] / (math.exp(
MONTHLY_B[month - 1] / (math.sin(math.radians(alt)))))
diff_horiz = 0.17 * dir_norm * math.sin(math.radians(alt))
dir_norm_rad.append(dir_norm * sky_clearness)
dif_horiz_rad.append(diff_horiz * sky_clearness)
except OverflowError:
# very small altitude values
dir_norm_rad.append(0)
dif_horiz_rad.append(0)
else:
# night time
dir_norm_rad.append(0)
dif_horiz_rad.append(0)
return dir_norm_rad, dif_horiz_rad | python | def ashrae_clear_sky(altitudes, month, sky_clearness=1):
"""Calculate solar flux for an original ASHRAE Clear Sky
Args:
altitudes: A list of solar altitudes in degrees
month: An integer (1-12) indicating the month the altitudes belong to
sky_clearness: A factor that will be multiplied by the output of
the model. This is to help account for locations where clear,
dry skies predominate (e.g., at high elevations) or,
conversely, where hazy and humid conditions are frequent. See
Threlkeld and Jordan (1958) for recommended values. Typical
values range from 0.95 to 1.05 and are usually never more
than 1.2. Default is set to 1.0.
Returns:
dir_norm_rad: A list of direct normal radiation values for each
of the connected altitudes in W/m2.
dif_horiz_rad: A list of diffuse horizontall radiation values for each
of the connected altitudes in W/m2.
"""
# apparent solar irradiation at air mass m = 0
MONTHLY_A = [1202, 1187, 1164, 1130, 1106, 1092, 1093, 1107, 1136,
1166, 1190, 1204]
# atmospheric extinction coefficient
MONTHLY_B = [0.141, 0.142, 0.149, 0.164, 0.177, 0.185, 0.186, 0.182,
0.165, 0.152, 0.144, 0.141]
dir_norm_rad = []
dif_horiz_rad = []
for i, alt in enumerate(altitudes):
if alt > 0:
try:
dir_norm = MONTHLY_A[month - 1] / (math.exp(
MONTHLY_B[month - 1] / (math.sin(math.radians(alt)))))
diff_horiz = 0.17 * dir_norm * math.sin(math.radians(alt))
dir_norm_rad.append(dir_norm * sky_clearness)
dif_horiz_rad.append(diff_horiz * sky_clearness)
except OverflowError:
# very small altitude values
dir_norm_rad.append(0)
dif_horiz_rad.append(0)
else:
# night time
dir_norm_rad.append(0)
dif_horiz_rad.append(0)
return dir_norm_rad, dif_horiz_rad | [
"def",
"ashrae_clear_sky",
"(",
"altitudes",
",",
"month",
",",
"sky_clearness",
"=",
"1",
")",
":",
"# apparent solar irradiation at air mass m = 0",
"MONTHLY_A",
"=",
"[",
"1202",
",",
"1187",
",",
"1164",
",",
"1130",
",",
"1106",
",",
"1092",
",",
"1093",
",",
"1107",
",",
"1136",
",",
"1166",
",",
"1190",
",",
"1204",
"]",
"# atmospheric extinction coefficient",
"MONTHLY_B",
"=",
"[",
"0.141",
",",
"0.142",
",",
"0.149",
",",
"0.164",
",",
"0.177",
",",
"0.185",
",",
"0.186",
",",
"0.182",
",",
"0.165",
",",
"0.152",
",",
"0.144",
",",
"0.141",
"]",
"dir_norm_rad",
"=",
"[",
"]",
"dif_horiz_rad",
"=",
"[",
"]",
"for",
"i",
",",
"alt",
"in",
"enumerate",
"(",
"altitudes",
")",
":",
"if",
"alt",
">",
"0",
":",
"try",
":",
"dir_norm",
"=",
"MONTHLY_A",
"[",
"month",
"-",
"1",
"]",
"/",
"(",
"math",
".",
"exp",
"(",
"MONTHLY_B",
"[",
"month",
"-",
"1",
"]",
"/",
"(",
"math",
".",
"sin",
"(",
"math",
".",
"radians",
"(",
"alt",
")",
")",
")",
")",
")",
"diff_horiz",
"=",
"0.17",
"*",
"dir_norm",
"*",
"math",
".",
"sin",
"(",
"math",
".",
"radians",
"(",
"alt",
")",
")",
"dir_norm_rad",
".",
"append",
"(",
"dir_norm",
"*",
"sky_clearness",
")",
"dif_horiz_rad",
".",
"append",
"(",
"diff_horiz",
"*",
"sky_clearness",
")",
"except",
"OverflowError",
":",
"# very small altitude values",
"dir_norm_rad",
".",
"append",
"(",
"0",
")",
"dif_horiz_rad",
".",
"append",
"(",
"0",
")",
"else",
":",
"# night time",
"dir_norm_rad",
".",
"append",
"(",
"0",
")",
"dif_horiz_rad",
".",
"append",
"(",
"0",
")",
"return",
"dir_norm_rad",
",",
"dif_horiz_rad"
] | Calculate solar flux for an original ASHRAE Clear Sky
Args:
altitudes: A list of solar altitudes in degrees
month: An integer (1-12) indicating the month the altitudes belong to
sky_clearness: A factor that will be multiplied by the output of
the model. This is to help account for locations where clear,
dry skies predominate (e.g., at high elevations) or,
conversely, where hazy and humid conditions are frequent. See
Threlkeld and Jordan (1958) for recommended values. Typical
values range from 0.95 to 1.05 and are usually never more
than 1.2. Default is set to 1.0.
Returns:
dir_norm_rad: A list of direct normal radiation values for each
of the connected altitudes in W/m2.
dif_horiz_rad: A list of diffuse horizontall radiation values for each
of the connected altitudes in W/m2. | [
"Calculate",
"solar",
"flux",
"for",
"an",
"original",
"ASHRAE",
"Clear",
"Sky"
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/skymodel.py#L11-L57 | train | 237,449 |
ladybug-tools/ladybug | ladybug/skymodel.py | zhang_huang_solar | def zhang_huang_solar(alt, cloud_cover, relative_humidity,
dry_bulb_present, dry_bulb_t3_hrs, wind_speed,
irr_0=1355):
"""Calculate global horizontal solar irradiance using the Zhang-Huang model.
Note:
[1] Zhang, Q.Y. and Huang, Y.J. 2002. "Development of typical year weather files
for Chinese locations", LBNL-51436, ASHRAE Transactions, Vol. 108, Part 2.
Args:
alt: A solar altitude in degrees.
cloud_cover: A float value between 0 and 10 that represents the sky cloud cover
in tenths (0 = clear; 10 = completely overcast)
relative_humidity: A float value between 0 and 100 that represents
the relative humidity in percent.
dry_bulb_present: A float value that represents the dry bulb
temperature at the time of interest (in degrees C).
dry_bulb_t3_hrs: A float value that represents the dry bulb
temperature at three hours before the time of interest (in degrees C).
wind_speed: A float value that represents the wind speed in m/s.
irr_0 = Optional extraterrestrial solar constant (W/m2).
Default is to use the average value over the earth's orbit (1355).
Returns:
glob_ir: A global horizontall radiation value in W/m2.
"""
# zhang-huang solar model regression constants
C0, C1, C2, C3, C4, C5, D_COEFF, K_COEFF = 0.5598, 0.4982, \
-0.6762, 0.02842, -0.00317, 0.014, -17.853, 0.843
# start assuming night time
glob_ir = 0
if alt > 0:
# get sin of the altitude
sin_alt = math.sin(math.radians(alt))
# shortened and converted versions of the input parameters
cc, rh, n_temp, n3_temp, w_spd = cloud_cover / 10.0, \
relative_humidity, dry_bulb_present, dry_bulb_t3_hrs, wind_speed
# calculate zhang-huang global radiation
glob_ir = ((irr_0 * sin_alt *
(C0 + (C1 * cc) + (C2 * cc**2) +
(C3 * (n_temp - n3_temp)) +
(C4 * rh) + (C5 * w_spd))) + D_COEFF) / K_COEFF
if glob_ir < 0:
glob_ir = 0
return glob_ir | python | def zhang_huang_solar(alt, cloud_cover, relative_humidity,
dry_bulb_present, dry_bulb_t3_hrs, wind_speed,
irr_0=1355):
"""Calculate global horizontal solar irradiance using the Zhang-Huang model.
Note:
[1] Zhang, Q.Y. and Huang, Y.J. 2002. "Development of typical year weather files
for Chinese locations", LBNL-51436, ASHRAE Transactions, Vol. 108, Part 2.
Args:
alt: A solar altitude in degrees.
cloud_cover: A float value between 0 and 10 that represents the sky cloud cover
in tenths (0 = clear; 10 = completely overcast)
relative_humidity: A float value between 0 and 100 that represents
the relative humidity in percent.
dry_bulb_present: A float value that represents the dry bulb
temperature at the time of interest (in degrees C).
dry_bulb_t3_hrs: A float value that represents the dry bulb
temperature at three hours before the time of interest (in degrees C).
wind_speed: A float value that represents the wind speed in m/s.
irr_0 = Optional extraterrestrial solar constant (W/m2).
Default is to use the average value over the earth's orbit (1355).
Returns:
glob_ir: A global horizontall radiation value in W/m2.
"""
# zhang-huang solar model regression constants
C0, C1, C2, C3, C4, C5, D_COEFF, K_COEFF = 0.5598, 0.4982, \
-0.6762, 0.02842, -0.00317, 0.014, -17.853, 0.843
# start assuming night time
glob_ir = 0
if alt > 0:
# get sin of the altitude
sin_alt = math.sin(math.radians(alt))
# shortened and converted versions of the input parameters
cc, rh, n_temp, n3_temp, w_spd = cloud_cover / 10.0, \
relative_humidity, dry_bulb_present, dry_bulb_t3_hrs, wind_speed
# calculate zhang-huang global radiation
glob_ir = ((irr_0 * sin_alt *
(C0 + (C1 * cc) + (C2 * cc**2) +
(C3 * (n_temp - n3_temp)) +
(C4 * rh) + (C5 * w_spd))) + D_COEFF) / K_COEFF
if glob_ir < 0:
glob_ir = 0
return glob_ir | [
"def",
"zhang_huang_solar",
"(",
"alt",
",",
"cloud_cover",
",",
"relative_humidity",
",",
"dry_bulb_present",
",",
"dry_bulb_t3_hrs",
",",
"wind_speed",
",",
"irr_0",
"=",
"1355",
")",
":",
"# zhang-huang solar model regression constants",
"C0",
",",
"C1",
",",
"C2",
",",
"C3",
",",
"C4",
",",
"C5",
",",
"D_COEFF",
",",
"K_COEFF",
"=",
"0.5598",
",",
"0.4982",
",",
"-",
"0.6762",
",",
"0.02842",
",",
"-",
"0.00317",
",",
"0.014",
",",
"-",
"17.853",
",",
"0.843",
"# start assuming night time",
"glob_ir",
"=",
"0",
"if",
"alt",
">",
"0",
":",
"# get sin of the altitude",
"sin_alt",
"=",
"math",
".",
"sin",
"(",
"math",
".",
"radians",
"(",
"alt",
")",
")",
"# shortened and converted versions of the input parameters",
"cc",
",",
"rh",
",",
"n_temp",
",",
"n3_temp",
",",
"w_spd",
"=",
"cloud_cover",
"/",
"10.0",
",",
"relative_humidity",
",",
"dry_bulb_present",
",",
"dry_bulb_t3_hrs",
",",
"wind_speed",
"# calculate zhang-huang global radiation",
"glob_ir",
"=",
"(",
"(",
"irr_0",
"*",
"sin_alt",
"*",
"(",
"C0",
"+",
"(",
"C1",
"*",
"cc",
")",
"+",
"(",
"C2",
"*",
"cc",
"**",
"2",
")",
"+",
"(",
"C3",
"*",
"(",
"n_temp",
"-",
"n3_temp",
")",
")",
"+",
"(",
"C4",
"*",
"rh",
")",
"+",
"(",
"C5",
"*",
"w_spd",
")",
")",
")",
"+",
"D_COEFF",
")",
"/",
"K_COEFF",
"if",
"glob_ir",
"<",
"0",
":",
"glob_ir",
"=",
"0",
"return",
"glob_ir"
] | Calculate global horizontal solar irradiance using the Zhang-Huang model.
Note:
[1] Zhang, Q.Y. and Huang, Y.J. 2002. "Development of typical year weather files
for Chinese locations", LBNL-51436, ASHRAE Transactions, Vol. 108, Part 2.
Args:
alt: A solar altitude in degrees.
cloud_cover: A float value between 0 and 10 that represents the sky cloud cover
in tenths (0 = clear; 10 = completely overcast)
relative_humidity: A float value between 0 and 100 that represents
the relative humidity in percent.
dry_bulb_present: A float value that represents the dry bulb
temperature at the time of interest (in degrees C).
dry_bulb_t3_hrs: A float value that represents the dry bulb
temperature at three hours before the time of interest (in degrees C).
wind_speed: A float value that represents the wind speed in m/s.
irr_0 = Optional extraterrestrial solar constant (W/m2).
Default is to use the average value over the earth's orbit (1355).
Returns:
glob_ir: A global horizontall radiation value in W/m2. | [
"Calculate",
"global",
"horizontal",
"solar",
"irradiance",
"using",
"the",
"Zhang",
"-",
"Huang",
"model",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/skymodel.py#L112-L161 | train | 237,450 |
ladybug-tools/ladybug | ladybug/skymodel.py | zhang_huang_solar_split | def zhang_huang_solar_split(altitudes, doys, cloud_cover, relative_humidity,
dry_bulb_present, dry_bulb_t3_hrs, wind_speed,
atm_pressure, use_disc=False):
"""Calculate direct and diffuse solar irradiance using the Zhang-Huang model.
By default, this function uses the DIRINT method (aka. Perez split) to split global
irradiance into direct and diffuse. This is the same method used by EnergyPlus.
Args:
altitudes: A list of solar altitudes in degrees.
doys: A list of days of the year that correspond to the altitudes.
cloud_cover: A list of float values between 0 and 10 that represents cloud cover
in tenths (0 = clear; 10 = completely overcast)
relative_humidity: A list of float values between 0 and 100 that represents
the relative humidity in percent.
dry_bulb_present: A list of float values that represents the dry bulb
temperature at the time of interest (in degrees C).
dry_bulb_t3_hrs: A list of float values that represents the dry bulb
temperature at three hours before the time of interest (in degrees C).
wind_speed: A list of float values that represents the wind speed in m/s.
atm_pressure: A list of float values that represent the
atmospheric pressure in Pa.
use_disc: Set to True to use the original DISC model as opposed to the
newer and more accurate DIRINT model. Default is False.
Returns:
dir_norm_rad: A list of direct normal radiation values for each
of the connected altitudes in W/m2.
dif_horiz_rad: A list of diffuse horizontall radiation values for each
of the connected altitudes in W/m2.
"""
# Calculate global horizontal irradiance using the original zhang-huang model
glob_ir = []
for i in range(len(altitudes)):
ghi = zhang_huang_solar(altitudes[i], cloud_cover[i], relative_humidity[i],
dry_bulb_present[i], dry_bulb_t3_hrs[i], wind_speed[i])
glob_ir.append(ghi)
if use_disc is False:
# Calculate dew point temperature to improve the splitting of direct + diffuse
temp_dew = [dew_point_from_db_rh(dry_bulb_present[i], relative_humidity[i])
for i in range(len(glob_ir))]
# Split global rad into direct + diffuse using dirint method (aka. Perez split)
dir_norm_rad = dirint(glob_ir, altitudes, doys, atm_pressure,
use_delta_kt_prime=True, temp_dew=temp_dew)
# Calculate diffuse horizontal from dni and ghi.
dif_horiz_rad = [glob_ir[i] -
(dir_norm_rad[i] * math.sin(math.radians(altitudes[i])))
for i in range(len(glob_ir))]
else:
dir_norm_rad = []
dif_horiz_rad = []
for i in range(len(glob_ir)):
dni, kt, am = disc(glob_ir[i], altitudes[i], doys[i], atm_pressure[i])
dhi = glob_ir[i] - (dni * math.sin(math.radians(altitudes[i])))
dir_norm_rad.append(dni)
dif_horiz_rad.append(dhi)
return dir_norm_rad, dif_horiz_rad | python | def zhang_huang_solar_split(altitudes, doys, cloud_cover, relative_humidity,
dry_bulb_present, dry_bulb_t3_hrs, wind_speed,
atm_pressure, use_disc=False):
"""Calculate direct and diffuse solar irradiance using the Zhang-Huang model.
By default, this function uses the DIRINT method (aka. Perez split) to split global
irradiance into direct and diffuse. This is the same method used by EnergyPlus.
Args:
altitudes: A list of solar altitudes in degrees.
doys: A list of days of the year that correspond to the altitudes.
cloud_cover: A list of float values between 0 and 10 that represents cloud cover
in tenths (0 = clear; 10 = completely overcast)
relative_humidity: A list of float values between 0 and 100 that represents
the relative humidity in percent.
dry_bulb_present: A list of float values that represents the dry bulb
temperature at the time of interest (in degrees C).
dry_bulb_t3_hrs: A list of float values that represents the dry bulb
temperature at three hours before the time of interest (in degrees C).
wind_speed: A list of float values that represents the wind speed in m/s.
atm_pressure: A list of float values that represent the
atmospheric pressure in Pa.
use_disc: Set to True to use the original DISC model as opposed to the
newer and more accurate DIRINT model. Default is False.
Returns:
dir_norm_rad: A list of direct normal radiation values for each
of the connected altitudes in W/m2.
dif_horiz_rad: A list of diffuse horizontall radiation values for each
of the connected altitudes in W/m2.
"""
# Calculate global horizontal irradiance using the original zhang-huang model
glob_ir = []
for i in range(len(altitudes)):
ghi = zhang_huang_solar(altitudes[i], cloud_cover[i], relative_humidity[i],
dry_bulb_present[i], dry_bulb_t3_hrs[i], wind_speed[i])
glob_ir.append(ghi)
if use_disc is False:
# Calculate dew point temperature to improve the splitting of direct + diffuse
temp_dew = [dew_point_from_db_rh(dry_bulb_present[i], relative_humidity[i])
for i in range(len(glob_ir))]
# Split global rad into direct + diffuse using dirint method (aka. Perez split)
dir_norm_rad = dirint(glob_ir, altitudes, doys, atm_pressure,
use_delta_kt_prime=True, temp_dew=temp_dew)
# Calculate diffuse horizontal from dni and ghi.
dif_horiz_rad = [glob_ir[i] -
(dir_norm_rad[i] * math.sin(math.radians(altitudes[i])))
for i in range(len(glob_ir))]
else:
dir_norm_rad = []
dif_horiz_rad = []
for i in range(len(glob_ir)):
dni, kt, am = disc(glob_ir[i], altitudes[i], doys[i], atm_pressure[i])
dhi = glob_ir[i] - (dni * math.sin(math.radians(altitudes[i])))
dir_norm_rad.append(dni)
dif_horiz_rad.append(dhi)
return dir_norm_rad, dif_horiz_rad | [
"def",
"zhang_huang_solar_split",
"(",
"altitudes",
",",
"doys",
",",
"cloud_cover",
",",
"relative_humidity",
",",
"dry_bulb_present",
",",
"dry_bulb_t3_hrs",
",",
"wind_speed",
",",
"atm_pressure",
",",
"use_disc",
"=",
"False",
")",
":",
"# Calculate global horizontal irradiance using the original zhang-huang model",
"glob_ir",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"altitudes",
")",
")",
":",
"ghi",
"=",
"zhang_huang_solar",
"(",
"altitudes",
"[",
"i",
"]",
",",
"cloud_cover",
"[",
"i",
"]",
",",
"relative_humidity",
"[",
"i",
"]",
",",
"dry_bulb_present",
"[",
"i",
"]",
",",
"dry_bulb_t3_hrs",
"[",
"i",
"]",
",",
"wind_speed",
"[",
"i",
"]",
")",
"glob_ir",
".",
"append",
"(",
"ghi",
")",
"if",
"use_disc",
"is",
"False",
":",
"# Calculate dew point temperature to improve the splitting of direct + diffuse",
"temp_dew",
"=",
"[",
"dew_point_from_db_rh",
"(",
"dry_bulb_present",
"[",
"i",
"]",
",",
"relative_humidity",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"glob_ir",
")",
")",
"]",
"# Split global rad into direct + diffuse using dirint method (aka. Perez split)",
"dir_norm_rad",
"=",
"dirint",
"(",
"glob_ir",
",",
"altitudes",
",",
"doys",
",",
"atm_pressure",
",",
"use_delta_kt_prime",
"=",
"True",
",",
"temp_dew",
"=",
"temp_dew",
")",
"# Calculate diffuse horizontal from dni and ghi.",
"dif_horiz_rad",
"=",
"[",
"glob_ir",
"[",
"i",
"]",
"-",
"(",
"dir_norm_rad",
"[",
"i",
"]",
"*",
"math",
".",
"sin",
"(",
"math",
".",
"radians",
"(",
"altitudes",
"[",
"i",
"]",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"glob_ir",
")",
")",
"]",
"else",
":",
"dir_norm_rad",
"=",
"[",
"]",
"dif_horiz_rad",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"glob_ir",
")",
")",
":",
"dni",
",",
"kt",
",",
"am",
"=",
"disc",
"(",
"glob_ir",
"[",
"i",
"]",
",",
"altitudes",
"[",
"i",
"]",
",",
"doys",
"[",
"i",
"]",
",",
"atm_pressure",
"[",
"i",
"]",
")",
"dhi",
"=",
"glob_ir",
"[",
"i",
"]",
"-",
"(",
"dni",
"*",
"math",
".",
"sin",
"(",
"math",
".",
"radians",
"(",
"altitudes",
"[",
"i",
"]",
")",
")",
")",
"dir_norm_rad",
".",
"append",
"(",
"dni",
")",
"dif_horiz_rad",
".",
"append",
"(",
"dhi",
")",
"return",
"dir_norm_rad",
",",
"dif_horiz_rad"
] | Calculate direct and diffuse solar irradiance using the Zhang-Huang model.
By default, this function uses the DIRINT method (aka. Perez split) to split global
irradiance into direct and diffuse. This is the same method used by EnergyPlus.
Args:
altitudes: A list of solar altitudes in degrees.
doys: A list of days of the year that correspond to the altitudes.
cloud_cover: A list of float values between 0 and 10 that represents cloud cover
in tenths (0 = clear; 10 = completely overcast)
relative_humidity: A list of float values between 0 and 100 that represents
the relative humidity in percent.
dry_bulb_present: A list of float values that represents the dry bulb
temperature at the time of interest (in degrees C).
dry_bulb_t3_hrs: A list of float values that represents the dry bulb
temperature at three hours before the time of interest (in degrees C).
wind_speed: A list of float values that represents the wind speed in m/s.
atm_pressure: A list of float values that represent the
atmospheric pressure in Pa.
use_disc: Set to True to use the original DISC model as opposed to the
newer and more accurate DIRINT model. Default is False.
Returns:
dir_norm_rad: A list of direct normal radiation values for each
of the connected altitudes in W/m2.
dif_horiz_rad: A list of diffuse horizontall radiation values for each
of the connected altitudes in W/m2. | [
"Calculate",
"direct",
"and",
"diffuse",
"solar",
"irradiance",
"using",
"the",
"Zhang",
"-",
"Huang",
"model",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/skymodel.py#L164-L224 | train | 237,451 |
ladybug-tools/ladybug | ladybug/skymodel.py | calc_horizontal_infrared | def calc_horizontal_infrared(sky_cover, dry_bulb, dew_point):
"""Calculate horizontal infrared radiation intensity.
See EnergyPlus Enrineering Reference for more information:
https://bigladdersoftware.com/epx/docs/8-9/engineering-reference/climate-calculations.html#sky-radiation-modeling
Note:
[1] Walton, G. N. 1983. Thermal Analysis Research Program Reference Manual.
NBSSIR 83-2655. National Bureau of Standards, p. 21.
[2] Clark, G. and C. Allen, “The Estimation of Atmospheric Radiation for
Clear and Cloudy Skies,” Proceedings 2nd National Passive Solar Conference
(AS/ISES), 1978, pp. 675-678.
Args:
sky_cover: A float value between 0 and 10 that represents the opaque
sky cover in tenths (0 = clear; 10 = completely overcast)
dry_bulb: A float value that represents the dry bulb temperature
in degrees C.
dew_point: A float value that represents the dew point temperature
in degrees C.
Returns:
horiz_ir: A horizontal infrared radiation intensity value in W/m2.
"""
# stefan-boltzmann constant
SIGMA = 5.6697e-8
# convert to kelvin
db_k = dry_bulb + 273.15
dp_k = dew_point + 273.15
# calculate sky emissivity and horizontal ir
sky_emiss = (0.787 + (0.764 * math.log(dp_k / 273.15))) * \
(1 + (0.022 * sky_cover) - (0.0035 * (sky_cover ** 2)) +
(0.00028 * (sky_cover ** 3)))
horiz_ir = sky_emiss * SIGMA * (db_k ** 4)
return horiz_ir | python | def calc_horizontal_infrared(sky_cover, dry_bulb, dew_point):
"""Calculate horizontal infrared radiation intensity.
See EnergyPlus Enrineering Reference for more information:
https://bigladdersoftware.com/epx/docs/8-9/engineering-reference/climate-calculations.html#sky-radiation-modeling
Note:
[1] Walton, G. N. 1983. Thermal Analysis Research Program Reference Manual.
NBSSIR 83-2655. National Bureau of Standards, p. 21.
[2] Clark, G. and C. Allen, “The Estimation of Atmospheric Radiation for
Clear and Cloudy Skies,” Proceedings 2nd National Passive Solar Conference
(AS/ISES), 1978, pp. 675-678.
Args:
sky_cover: A float value between 0 and 10 that represents the opaque
sky cover in tenths (0 = clear; 10 = completely overcast)
dry_bulb: A float value that represents the dry bulb temperature
in degrees C.
dew_point: A float value that represents the dew point temperature
in degrees C.
Returns:
horiz_ir: A horizontal infrared radiation intensity value in W/m2.
"""
# stefan-boltzmann constant
SIGMA = 5.6697e-8
# convert to kelvin
db_k = dry_bulb + 273.15
dp_k = dew_point + 273.15
# calculate sky emissivity and horizontal ir
sky_emiss = (0.787 + (0.764 * math.log(dp_k / 273.15))) * \
(1 + (0.022 * sky_cover) - (0.0035 * (sky_cover ** 2)) +
(0.00028 * (sky_cover ** 3)))
horiz_ir = sky_emiss * SIGMA * (db_k ** 4)
return horiz_ir | [
"def",
"calc_horizontal_infrared",
"(",
"sky_cover",
",",
"dry_bulb",
",",
"dew_point",
")",
":",
"# stefan-boltzmann constant",
"SIGMA",
"=",
"5.6697e-8",
"# convert to kelvin",
"db_k",
"=",
"dry_bulb",
"+",
"273.15",
"dp_k",
"=",
"dew_point",
"+",
"273.15",
"# calculate sky emissivity and horizontal ir",
"sky_emiss",
"=",
"(",
"0.787",
"+",
"(",
"0.764",
"*",
"math",
".",
"log",
"(",
"dp_k",
"/",
"273.15",
")",
")",
")",
"*",
"(",
"1",
"+",
"(",
"0.022",
"*",
"sky_cover",
")",
"-",
"(",
"0.0035",
"*",
"(",
"sky_cover",
"**",
"2",
")",
")",
"+",
"(",
"0.00028",
"*",
"(",
"sky_cover",
"**",
"3",
")",
")",
")",
"horiz_ir",
"=",
"sky_emiss",
"*",
"SIGMA",
"*",
"(",
"db_k",
"**",
"4",
")",
"return",
"horiz_ir"
] | Calculate horizontal infrared radiation intensity.
See EnergyPlus Enrineering Reference for more information:
https://bigladdersoftware.com/epx/docs/8-9/engineering-reference/climate-calculations.html#sky-radiation-modeling
Note:
[1] Walton, G. N. 1983. Thermal Analysis Research Program Reference Manual.
NBSSIR 83-2655. National Bureau of Standards, p. 21.
[2] Clark, G. and C. Allen, “The Estimation of Atmospheric Radiation for
Clear and Cloudy Skies,” Proceedings 2nd National Passive Solar Conference
(AS/ISES), 1978, pp. 675-678.
Args:
sky_cover: A float value between 0 and 10 that represents the opaque
sky cover in tenths (0 = clear; 10 = completely overcast)
dry_bulb: A float value that represents the dry bulb temperature
in degrees C.
dew_point: A float value that represents the dew point temperature
in degrees C.
Returns:
horiz_ir: A horizontal infrared radiation intensity value in W/m2. | [
"Calculate",
"horizontal",
"infrared",
"radiation",
"intensity",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/skymodel.py#L230-L267 | train | 237,452 |
ladybug-tools/ladybug | ladybug/legendparameters.py | LegendParameters.set_domain | def set_domain(self, values):
"""Set domain of the colors based on min and max of a list of values."""
_flattenedList = sorted(flatten(values))
self.domain = tuple(_flattenedList[0] if d == 'min' else d for d in self.domain)
self.domain = tuple(_flattenedList[-1] if d == 'max' else d for d in self.domain) | python | def set_domain(self, values):
"""Set domain of the colors based on min and max of a list of values."""
_flattenedList = sorted(flatten(values))
self.domain = tuple(_flattenedList[0] if d == 'min' else d for d in self.domain)
self.domain = tuple(_flattenedList[-1] if d == 'max' else d for d in self.domain) | [
"def",
"set_domain",
"(",
"self",
",",
"values",
")",
":",
"_flattenedList",
"=",
"sorted",
"(",
"flatten",
"(",
"values",
")",
")",
"self",
".",
"domain",
"=",
"tuple",
"(",
"_flattenedList",
"[",
"0",
"]",
"if",
"d",
"==",
"'min'",
"else",
"d",
"for",
"d",
"in",
"self",
".",
"domain",
")",
"self",
".",
"domain",
"=",
"tuple",
"(",
"_flattenedList",
"[",
"-",
"1",
"]",
"if",
"d",
"==",
"'max'",
"else",
"d",
"for",
"d",
"in",
"self",
".",
"domain",
")"
] | Set domain of the colors based on min and max of a list of values. | [
"Set",
"domain",
"of",
"the",
"colors",
"based",
"on",
"min",
"and",
"max",
"of",
"a",
"list",
"of",
"values",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/legendparameters.py#L80-L84 | train | 237,453 |
ladybug-tools/ladybug | ladybug/datacollection.py | HourlyDiscontinuousCollection.timestep_text | def timestep_text(self):
"""Return a text string representing the timestep of the collection."""
if self.header.analysis_period.timestep == 1:
return 'Hourly'
else:
return '{} Minute'.format(int(60 / self.header.analysis_period.timestep)) | python | def timestep_text(self):
"""Return a text string representing the timestep of the collection."""
if self.header.analysis_period.timestep == 1:
return 'Hourly'
else:
return '{} Minute'.format(int(60 / self.header.analysis_period.timestep)) | [
"def",
"timestep_text",
"(",
"self",
")",
":",
"if",
"self",
".",
"header",
".",
"analysis_period",
".",
"timestep",
"==",
"1",
":",
"return",
"'Hourly'",
"else",
":",
"return",
"'{} Minute'",
".",
"format",
"(",
"int",
"(",
"60",
"/",
"self",
".",
"header",
".",
"analysis_period",
".",
"timestep",
")",
")"
] | Return a text string representing the timestep of the collection. | [
"Return",
"a",
"text",
"string",
"representing",
"the",
"timestep",
"of",
"the",
"collection",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L96-L101 | train | 237,454 |
ladybug-tools/ladybug | ladybug/datacollection.py | HourlyDiscontinuousCollection.moys_dict | def moys_dict(self):
"""Return a dictionary of this collection's values where the keys are the moys.
This is useful for aligning the values with another list of datetimes.
"""
moy_dict = {}
for val, dt in zip(self.values, self.datetimes):
moy_dict[dt.moy] = val
return moy_dict | python | def moys_dict(self):
"""Return a dictionary of this collection's values where the keys are the moys.
This is useful for aligning the values with another list of datetimes.
"""
moy_dict = {}
for val, dt in zip(self.values, self.datetimes):
moy_dict[dt.moy] = val
return moy_dict | [
"def",
"moys_dict",
"(",
"self",
")",
":",
"moy_dict",
"=",
"{",
"}",
"for",
"val",
",",
"dt",
"in",
"zip",
"(",
"self",
".",
"values",
",",
"self",
".",
"datetimes",
")",
":",
"moy_dict",
"[",
"dt",
".",
"moy",
"]",
"=",
"val",
"return",
"moy_dict"
] | Return a dictionary of this collection's values where the keys are the moys.
This is useful for aligning the values with another list of datetimes. | [
"Return",
"a",
"dictionary",
"of",
"this",
"collection",
"s",
"values",
"where",
"the",
"keys",
"are",
"the",
"moys",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L104-L112 | train | 237,455 |
ladybug-tools/ladybug | ladybug/datacollection.py | HourlyDiscontinuousCollection.filter_by_analysis_period | def filter_by_analysis_period(self, analysis_period):
"""
Filter a Data Collection based on an analysis period.
Args:
analysis period: A Ladybug analysis period
Return:
A new Data Collection with filtered data
"""
self._check_analysis_period(analysis_period)
_filtered_data = self.filter_by_moys(analysis_period.moys)
_filtered_data.header._analysis_period = analysis_period
return _filtered_data | python | def filter_by_analysis_period(self, analysis_period):
"""
Filter a Data Collection based on an analysis period.
Args:
analysis period: A Ladybug analysis period
Return:
A new Data Collection with filtered data
"""
self._check_analysis_period(analysis_period)
_filtered_data = self.filter_by_moys(analysis_period.moys)
_filtered_data.header._analysis_period = analysis_period
return _filtered_data | [
"def",
"filter_by_analysis_period",
"(",
"self",
",",
"analysis_period",
")",
":",
"self",
".",
"_check_analysis_period",
"(",
"analysis_period",
")",
"_filtered_data",
"=",
"self",
".",
"filter_by_moys",
"(",
"analysis_period",
".",
"moys",
")",
"_filtered_data",
".",
"header",
".",
"_analysis_period",
"=",
"analysis_period",
"return",
"_filtered_data"
] | Filter a Data Collection based on an analysis period.
Args:
analysis period: A Ladybug analysis period
Return:
A new Data Collection with filtered data | [
"Filter",
"a",
"Data",
"Collection",
"based",
"on",
"an",
"analysis",
"period",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L114-L127 | train | 237,456 |
ladybug-tools/ladybug | ladybug/datacollection.py | HourlyDiscontinuousCollection.group_by_month_per_hour | def group_by_month_per_hour(self):
"""Return a dictionary of this collection's values grouped by each month per hour.
Key values are tuples of 2 integers:
The first represents the month of the year between 1-12.
The first represents the hour of the day between 0-24.
(eg. (12, 23) for December at 11 PM)
"""
data_by_month_per_hour = OrderedDict()
for m in xrange(1, 13):
for h in xrange(0, 24):
data_by_month_per_hour[(m, h)] = []
for v, dt in zip(self.values, self.datetimes):
data_by_month_per_hour[(dt.month, dt.hour)].append(v)
return data_by_month_per_hour | python | def group_by_month_per_hour(self):
"""Return a dictionary of this collection's values grouped by each month per hour.
Key values are tuples of 2 integers:
The first represents the month of the year between 1-12.
The first represents the hour of the day between 0-24.
(eg. (12, 23) for December at 11 PM)
"""
data_by_month_per_hour = OrderedDict()
for m in xrange(1, 13):
for h in xrange(0, 24):
data_by_month_per_hour[(m, h)] = []
for v, dt in zip(self.values, self.datetimes):
data_by_month_per_hour[(dt.month, dt.hour)].append(v)
return data_by_month_per_hour | [
"def",
"group_by_month_per_hour",
"(",
"self",
")",
":",
"data_by_month_per_hour",
"=",
"OrderedDict",
"(",
")",
"for",
"m",
"in",
"xrange",
"(",
"1",
",",
"13",
")",
":",
"for",
"h",
"in",
"xrange",
"(",
"0",
",",
"24",
")",
":",
"data_by_month_per_hour",
"[",
"(",
"m",
",",
"h",
")",
"]",
"=",
"[",
"]",
"for",
"v",
",",
"dt",
"in",
"zip",
"(",
"self",
".",
"values",
",",
"self",
".",
"datetimes",
")",
":",
"data_by_month_per_hour",
"[",
"(",
"dt",
".",
"month",
",",
"dt",
".",
"hour",
")",
"]",
".",
"append",
"(",
"v",
")",
"return",
"data_by_month_per_hour"
] | Return a dictionary of this collection's values grouped by each month per hour.
Key values are tuples of 2 integers:
The first represents the month of the year between 1-12.
The first represents the hour of the day between 0-24.
(eg. (12, 23) for December at 11 PM) | [
"Return",
"a",
"dictionary",
"of",
"this",
"collection",
"s",
"values",
"grouped",
"by",
"each",
"month",
"per",
"hour",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L214-L228 | train | 237,457 |
ladybug-tools/ladybug | ladybug/datacollection.py | HourlyDiscontinuousCollection.interpolate_holes | def interpolate_holes(self):
"""Linearly interpolate over holes in this collection to make it continuous.
Returns:
continuous_collection: A HourlyContinuousCollection with the same data
as this collection but with missing data filled by means of a
linear interpolation.
"""
# validate analysis_period and use the resulting period to generate datetimes
assert self.validated_a_period is True, 'validated_a_period property must be' \
' True to use interpolate_holes(). Run validate_analysis_period().'
mins_per_step = int(60 / self.header.analysis_period.timestep)
new_datetimes = self.header.analysis_period.datetimes
new_values = []
# if the first steps are a hole, duplicate the first value.
i = 0
if new_datetimes[0] != self.datetimes[0]:
n_steps = int((self.datetimes[0].moy - new_datetimes[0].moy) / mins_per_step)
new_values.extend([self._values[0]] * n_steps)
i = n_steps - 1
# go through the values interpolating any holes.
for j in xrange(len(self._values)):
if new_datetimes[i] == self.datetimes[j]: # there is no hole.
new_values.append(self._values[j])
i += 1
else: # there is a hole between this step and the previous step.
n_steps = int((self.datetimes[j].moy - new_datetimes[i].moy)
/ mins_per_step)
intp_vals = self._xxrange(self._values[j - 1], self._values[j], n_steps)
new_values.extend(list(intp_vals)[1:] + [self._values[j]])
i += n_steps
# if the last steps are a hole duplicate the last value.
if len(new_values) != len(new_datetimes):
n_steps = len(new_datetimes) - len(new_values)
new_values.extend([self._values[-1]] * n_steps)
# build the new continuous data collection.
return HourlyContinuousCollection(self.header.duplicate(), new_values) | python | def interpolate_holes(self):
"""Linearly interpolate over holes in this collection to make it continuous.
Returns:
continuous_collection: A HourlyContinuousCollection with the same data
as this collection but with missing data filled by means of a
linear interpolation.
"""
# validate analysis_period and use the resulting period to generate datetimes
assert self.validated_a_period is True, 'validated_a_period property must be' \
' True to use interpolate_holes(). Run validate_analysis_period().'
mins_per_step = int(60 / self.header.analysis_period.timestep)
new_datetimes = self.header.analysis_period.datetimes
new_values = []
# if the first steps are a hole, duplicate the first value.
i = 0
if new_datetimes[0] != self.datetimes[0]:
n_steps = int((self.datetimes[0].moy - new_datetimes[0].moy) / mins_per_step)
new_values.extend([self._values[0]] * n_steps)
i = n_steps - 1
# go through the values interpolating any holes.
for j in xrange(len(self._values)):
if new_datetimes[i] == self.datetimes[j]: # there is no hole.
new_values.append(self._values[j])
i += 1
else: # there is a hole between this step and the previous step.
n_steps = int((self.datetimes[j].moy - new_datetimes[i].moy)
/ mins_per_step)
intp_vals = self._xxrange(self._values[j - 1], self._values[j], n_steps)
new_values.extend(list(intp_vals)[1:] + [self._values[j]])
i += n_steps
# if the last steps are a hole duplicate the last value.
if len(new_values) != len(new_datetimes):
n_steps = len(new_datetimes) - len(new_values)
new_values.extend([self._values[-1]] * n_steps)
# build the new continuous data collection.
return HourlyContinuousCollection(self.header.duplicate(), new_values) | [
"def",
"interpolate_holes",
"(",
"self",
")",
":",
"# validate analysis_period and use the resulting period to generate datetimes",
"assert",
"self",
".",
"validated_a_period",
"is",
"True",
",",
"'validated_a_period property must be'",
"' True to use interpolate_holes(). Run validate_analysis_period().'",
"mins_per_step",
"=",
"int",
"(",
"60",
"/",
"self",
".",
"header",
".",
"analysis_period",
".",
"timestep",
")",
"new_datetimes",
"=",
"self",
".",
"header",
".",
"analysis_period",
".",
"datetimes",
"new_values",
"=",
"[",
"]",
"# if the first steps are a hole, duplicate the first value.",
"i",
"=",
"0",
"if",
"new_datetimes",
"[",
"0",
"]",
"!=",
"self",
".",
"datetimes",
"[",
"0",
"]",
":",
"n_steps",
"=",
"int",
"(",
"(",
"self",
".",
"datetimes",
"[",
"0",
"]",
".",
"moy",
"-",
"new_datetimes",
"[",
"0",
"]",
".",
"moy",
")",
"/",
"mins_per_step",
")",
"new_values",
".",
"extend",
"(",
"[",
"self",
".",
"_values",
"[",
"0",
"]",
"]",
"*",
"n_steps",
")",
"i",
"=",
"n_steps",
"-",
"1",
"# go through the values interpolating any holes.",
"for",
"j",
"in",
"xrange",
"(",
"len",
"(",
"self",
".",
"_values",
")",
")",
":",
"if",
"new_datetimes",
"[",
"i",
"]",
"==",
"self",
".",
"datetimes",
"[",
"j",
"]",
":",
"# there is no hole.",
"new_values",
".",
"append",
"(",
"self",
".",
"_values",
"[",
"j",
"]",
")",
"i",
"+=",
"1",
"else",
":",
"# there is a hole between this step and the previous step.",
"n_steps",
"=",
"int",
"(",
"(",
"self",
".",
"datetimes",
"[",
"j",
"]",
".",
"moy",
"-",
"new_datetimes",
"[",
"i",
"]",
".",
"moy",
")",
"/",
"mins_per_step",
")",
"intp_vals",
"=",
"self",
".",
"_xxrange",
"(",
"self",
".",
"_values",
"[",
"j",
"-",
"1",
"]",
",",
"self",
".",
"_values",
"[",
"j",
"]",
",",
"n_steps",
")",
"new_values",
".",
"extend",
"(",
"list",
"(",
"intp_vals",
")",
"[",
"1",
":",
"]",
"+",
"[",
"self",
".",
"_values",
"[",
"j",
"]",
"]",
")",
"i",
"+=",
"n_steps",
"# if the last steps are a hole duplicate the last value.",
"if",
"len",
"(",
"new_values",
")",
"!=",
"len",
"(",
"new_datetimes",
")",
":",
"n_steps",
"=",
"len",
"(",
"new_datetimes",
")",
"-",
"len",
"(",
"new_values",
")",
"new_values",
".",
"extend",
"(",
"[",
"self",
".",
"_values",
"[",
"-",
"1",
"]",
"]",
"*",
"n_steps",
")",
"# build the new continuous data collection.",
"return",
"HourlyContinuousCollection",
"(",
"self",
".",
"header",
".",
"duplicate",
"(",
")",
",",
"new_values",
")"
] | Linearly interpolate over holes in this collection to make it continuous.
Returns:
continuous_collection: A HourlyContinuousCollection with the same data
as this collection but with missing data filled by means of a
linear interpolation. | [
"Linearly",
"interpolate",
"over",
"holes",
"in",
"this",
"collection",
"to",
"make",
"it",
"continuous",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L247-L287 | train | 237,458 |
ladybug-tools/ladybug | ladybug/datacollection.py | HourlyDiscontinuousCollection.cull_to_timestep | def cull_to_timestep(self, timestep=1):
"""Get a collection with only datetimes that fit a timestep."""
valid_s = self.header.analysis_period.VALIDTIMESTEPS.keys()
assert timestep in valid_s, \
'timestep {} is not valid. Choose from: {}'.format(timestep, valid_s)
new_ap, new_values, new_datetimes = self._timestep_cull(timestep)
new_header = self.header.duplicate()
new_header._analysis_period = new_ap
new_coll = HourlyDiscontinuousCollection(
new_header, new_values, new_datetimes)
new_coll._validated_a_period = True
return new_coll | python | def cull_to_timestep(self, timestep=1):
"""Get a collection with only datetimes that fit a timestep."""
valid_s = self.header.analysis_period.VALIDTIMESTEPS.keys()
assert timestep in valid_s, \
'timestep {} is not valid. Choose from: {}'.format(timestep, valid_s)
new_ap, new_values, new_datetimes = self._timestep_cull(timestep)
new_header = self.header.duplicate()
new_header._analysis_period = new_ap
new_coll = HourlyDiscontinuousCollection(
new_header, new_values, new_datetimes)
new_coll._validated_a_period = True
return new_coll | [
"def",
"cull_to_timestep",
"(",
"self",
",",
"timestep",
"=",
"1",
")",
":",
"valid_s",
"=",
"self",
".",
"header",
".",
"analysis_period",
".",
"VALIDTIMESTEPS",
".",
"keys",
"(",
")",
"assert",
"timestep",
"in",
"valid_s",
",",
"'timestep {} is not valid. Choose from: {}'",
".",
"format",
"(",
"timestep",
",",
"valid_s",
")",
"new_ap",
",",
"new_values",
",",
"new_datetimes",
"=",
"self",
".",
"_timestep_cull",
"(",
"timestep",
")",
"new_header",
"=",
"self",
".",
"header",
".",
"duplicate",
"(",
")",
"new_header",
".",
"_analysis_period",
"=",
"new_ap",
"new_coll",
"=",
"HourlyDiscontinuousCollection",
"(",
"new_header",
",",
"new_values",
",",
"new_datetimes",
")",
"new_coll",
".",
"_validated_a_period",
"=",
"True",
"return",
"new_coll"
] | Get a collection with only datetimes that fit a timestep. | [
"Get",
"a",
"collection",
"with",
"only",
"datetimes",
"that",
"fit",
"a",
"timestep",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L289-L301 | train | 237,459 |
ladybug-tools/ladybug | ladybug/datacollection.py | HourlyDiscontinuousCollection.convert_to_culled_timestep | def convert_to_culled_timestep(self, timestep=1):
"""Convert this collection to one that only has datetimes that fit a timestep."""
valid_s = self.header.analysis_period.VALIDTIMESTEPS.keys()
assert timestep in valid_s, \
'timestep {} is not valid. Choose from: {}'.format(timestep, valid_s)
new_ap, new_values, new_datetimes = self._timestep_cull(timestep)
self.header._analysis_period = new_ap
self._values = new_values
self._datetimes = new_datetimes | python | def convert_to_culled_timestep(self, timestep=1):
"""Convert this collection to one that only has datetimes that fit a timestep."""
valid_s = self.header.analysis_period.VALIDTIMESTEPS.keys()
assert timestep in valid_s, \
'timestep {} is not valid. Choose from: {}'.format(timestep, valid_s)
new_ap, new_values, new_datetimes = self._timestep_cull(timestep)
self.header._analysis_period = new_ap
self._values = new_values
self._datetimes = new_datetimes | [
"def",
"convert_to_culled_timestep",
"(",
"self",
",",
"timestep",
"=",
"1",
")",
":",
"valid_s",
"=",
"self",
".",
"header",
".",
"analysis_period",
".",
"VALIDTIMESTEPS",
".",
"keys",
"(",
")",
"assert",
"timestep",
"in",
"valid_s",
",",
"'timestep {} is not valid. Choose from: {}'",
".",
"format",
"(",
"timestep",
",",
"valid_s",
")",
"new_ap",
",",
"new_values",
",",
"new_datetimes",
"=",
"self",
".",
"_timestep_cull",
"(",
"timestep",
")",
"self",
".",
"header",
".",
"_analysis_period",
"=",
"new_ap",
"self",
".",
"_values",
"=",
"new_values",
"self",
".",
"_datetimes",
"=",
"new_datetimes"
] | Convert this collection to one that only has datetimes that fit a timestep. | [
"Convert",
"this",
"collection",
"to",
"one",
"that",
"only",
"has",
"datetimes",
"that",
"fit",
"a",
"timestep",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L303-L312 | train | 237,460 |
ladybug-tools/ladybug | ladybug/datacollection.py | HourlyDiscontinuousCollection._xxrange | def _xxrange(self, start, end, step_count):
"""Generate n values between start and end."""
_step = (end - start) / float(step_count)
return (start + (i * _step) for i in xrange(int(step_count))) | python | def _xxrange(self, start, end, step_count):
"""Generate n values between start and end."""
_step = (end - start) / float(step_count)
return (start + (i * _step) for i in xrange(int(step_count))) | [
"def",
"_xxrange",
"(",
"self",
",",
"start",
",",
"end",
",",
"step_count",
")",
":",
"_step",
"=",
"(",
"end",
"-",
"start",
")",
"/",
"float",
"(",
"step_count",
")",
"return",
"(",
"start",
"+",
"(",
"i",
"*",
"_step",
")",
"for",
"i",
"in",
"xrange",
"(",
"int",
"(",
"step_count",
")",
")",
")"
] | Generate n values between start and end. | [
"Generate",
"n",
"values",
"between",
"start",
"and",
"end",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L409-L412 | train | 237,461 |
ladybug-tools/ladybug | ladybug/datacollection.py | HourlyDiscontinuousCollection._filter_by_moys_slow | def _filter_by_moys_slow(self, moys):
"""Filter the Data Collection with a slow method that always works."""
_filt_values = []
_filt_datetimes = []
for i, d in enumerate(self.datetimes):
if d.moy in moys:
_filt_datetimes.append(d)
_filt_values.append(self._values[i])
return _filt_values, _filt_datetimes | python | def _filter_by_moys_slow(self, moys):
"""Filter the Data Collection with a slow method that always works."""
_filt_values = []
_filt_datetimes = []
for i, d in enumerate(self.datetimes):
if d.moy in moys:
_filt_datetimes.append(d)
_filt_values.append(self._values[i])
return _filt_values, _filt_datetimes | [
"def",
"_filter_by_moys_slow",
"(",
"self",
",",
"moys",
")",
":",
"_filt_values",
"=",
"[",
"]",
"_filt_datetimes",
"=",
"[",
"]",
"for",
"i",
",",
"d",
"in",
"enumerate",
"(",
"self",
".",
"datetimes",
")",
":",
"if",
"d",
".",
"moy",
"in",
"moys",
":",
"_filt_datetimes",
".",
"append",
"(",
"d",
")",
"_filt_values",
".",
"append",
"(",
"self",
".",
"_values",
"[",
"i",
"]",
")",
"return",
"_filt_values",
",",
"_filt_datetimes"
] | Filter the Data Collection with a slow method that always works. | [
"Filter",
"the",
"Data",
"Collection",
"with",
"a",
"slow",
"method",
"that",
"always",
"works",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L414-L422 | train | 237,462 |
ladybug-tools/ladybug | ladybug/datacollection.py | HourlyDiscontinuousCollection._timestep_cull | def _timestep_cull(self, timestep):
"""Cull out values that do not fit a timestep."""
new_values = []
new_datetimes = []
mins_per_step = int(60 / timestep)
for i, date_t in enumerate(self.datetimes):
if date_t.moy % mins_per_step == 0:
new_datetimes.append(date_t)
new_values.append(self.values[i])
a_per = self.header.analysis_period
new_ap = AnalysisPeriod(a_per.st_month, a_per.st_day, a_per.st_hour,
a_per.end_month, a_per.end_day, a_per.end_hour,
timestep, a_per.is_leap_year)
return new_ap, new_values, new_datetimes | python | def _timestep_cull(self, timestep):
"""Cull out values that do not fit a timestep."""
new_values = []
new_datetimes = []
mins_per_step = int(60 / timestep)
for i, date_t in enumerate(self.datetimes):
if date_t.moy % mins_per_step == 0:
new_datetimes.append(date_t)
new_values.append(self.values[i])
a_per = self.header.analysis_period
new_ap = AnalysisPeriod(a_per.st_month, a_per.st_day, a_per.st_hour,
a_per.end_month, a_per.end_day, a_per.end_hour,
timestep, a_per.is_leap_year)
return new_ap, new_values, new_datetimes | [
"def",
"_timestep_cull",
"(",
"self",
",",
"timestep",
")",
":",
"new_values",
"=",
"[",
"]",
"new_datetimes",
"=",
"[",
"]",
"mins_per_step",
"=",
"int",
"(",
"60",
"/",
"timestep",
")",
"for",
"i",
",",
"date_t",
"in",
"enumerate",
"(",
"self",
".",
"datetimes",
")",
":",
"if",
"date_t",
".",
"moy",
"%",
"mins_per_step",
"==",
"0",
":",
"new_datetimes",
".",
"append",
"(",
"date_t",
")",
"new_values",
".",
"append",
"(",
"self",
".",
"values",
"[",
"i",
"]",
")",
"a_per",
"=",
"self",
".",
"header",
".",
"analysis_period",
"new_ap",
"=",
"AnalysisPeriod",
"(",
"a_per",
".",
"st_month",
",",
"a_per",
".",
"st_day",
",",
"a_per",
".",
"st_hour",
",",
"a_per",
".",
"end_month",
",",
"a_per",
".",
"end_day",
",",
"a_per",
".",
"end_hour",
",",
"timestep",
",",
"a_per",
".",
"is_leap_year",
")",
"return",
"new_ap",
",",
"new_values",
",",
"new_datetimes"
] | Cull out values that do not fit a timestep. | [
"Cull",
"out",
"values",
"that",
"do",
"not",
"fit",
"a",
"timestep",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L424-L437 | train | 237,463 |
ladybug-tools/ladybug | ladybug/datacollection.py | HourlyDiscontinuousCollection._time_interval_operation | def _time_interval_operation(self, interval, operation, percentile=0):
"""Get a collection of a certain time interval with a given math operation."""
# retrive the function that correctly describes the operation
if operation == 'average':
funct = self._average
elif operation == 'total':
funct = self._total
else:
assert 0 <= percentile <= 100, \
'percentile must be between 0 and 100. Got {}'.format(percentile)
funct = self._get_percentile_function(percentile)
# retrive the data that correctly describes the time interval
if interval == 'monthly':
data_dict = self.group_by_month()
dates = self.header.analysis_period.months_int
elif interval == 'daily':
data_dict = self.group_by_day()
dates = self.header.analysis_period.doys_int
elif interval == 'monthlyperhour':
data_dict = self.group_by_month_per_hour()
dates = self.header.analysis_period.months_per_hour
else:
raise ValueError('Invalid input value for interval: {}'.format(interval))
# get the data and header for the new collection
new_data, d_times = [], []
for i in dates:
vals = data_dict[i]
if vals != []:
new_data.append(funct(vals))
d_times.append(i)
new_header = self.header.duplicate()
if operation == 'percentile':
new_header.metadata['operation'] = '{} percentile'.format(percentile)
else:
new_header.metadata['operation'] = operation
# build the final data collection
if interval == 'monthly':
collection = MonthlyCollection(new_header, new_data, d_times)
elif interval == 'daily':
collection = DailyCollection(new_header, new_data, d_times)
elif interval == 'monthlyperhour':
collection = MonthlyPerHourCollection(new_header, new_data, d_times)
collection._validated_a_period = True
return collection | python | def _time_interval_operation(self, interval, operation, percentile=0):
"""Get a collection of a certain time interval with a given math operation."""
# retrive the function that correctly describes the operation
if operation == 'average':
funct = self._average
elif operation == 'total':
funct = self._total
else:
assert 0 <= percentile <= 100, \
'percentile must be between 0 and 100. Got {}'.format(percentile)
funct = self._get_percentile_function(percentile)
# retrive the data that correctly describes the time interval
if interval == 'monthly':
data_dict = self.group_by_month()
dates = self.header.analysis_period.months_int
elif interval == 'daily':
data_dict = self.group_by_day()
dates = self.header.analysis_period.doys_int
elif interval == 'monthlyperhour':
data_dict = self.group_by_month_per_hour()
dates = self.header.analysis_period.months_per_hour
else:
raise ValueError('Invalid input value for interval: {}'.format(interval))
# get the data and header for the new collection
new_data, d_times = [], []
for i in dates:
vals = data_dict[i]
if vals != []:
new_data.append(funct(vals))
d_times.append(i)
new_header = self.header.duplicate()
if operation == 'percentile':
new_header.metadata['operation'] = '{} percentile'.format(percentile)
else:
new_header.metadata['operation'] = operation
# build the final data collection
if interval == 'monthly':
collection = MonthlyCollection(new_header, new_data, d_times)
elif interval == 'daily':
collection = DailyCollection(new_header, new_data, d_times)
elif interval == 'monthlyperhour':
collection = MonthlyPerHourCollection(new_header, new_data, d_times)
collection._validated_a_period = True
return collection | [
"def",
"_time_interval_operation",
"(",
"self",
",",
"interval",
",",
"operation",
",",
"percentile",
"=",
"0",
")",
":",
"# retrive the function that correctly describes the operation",
"if",
"operation",
"==",
"'average'",
":",
"funct",
"=",
"self",
".",
"_average",
"elif",
"operation",
"==",
"'total'",
":",
"funct",
"=",
"self",
".",
"_total",
"else",
":",
"assert",
"0",
"<=",
"percentile",
"<=",
"100",
",",
"'percentile must be between 0 and 100. Got {}'",
".",
"format",
"(",
"percentile",
")",
"funct",
"=",
"self",
".",
"_get_percentile_function",
"(",
"percentile",
")",
"# retrive the data that correctly describes the time interval",
"if",
"interval",
"==",
"'monthly'",
":",
"data_dict",
"=",
"self",
".",
"group_by_month",
"(",
")",
"dates",
"=",
"self",
".",
"header",
".",
"analysis_period",
".",
"months_int",
"elif",
"interval",
"==",
"'daily'",
":",
"data_dict",
"=",
"self",
".",
"group_by_day",
"(",
")",
"dates",
"=",
"self",
".",
"header",
".",
"analysis_period",
".",
"doys_int",
"elif",
"interval",
"==",
"'monthlyperhour'",
":",
"data_dict",
"=",
"self",
".",
"group_by_month_per_hour",
"(",
")",
"dates",
"=",
"self",
".",
"header",
".",
"analysis_period",
".",
"months_per_hour",
"else",
":",
"raise",
"ValueError",
"(",
"'Invalid input value for interval: {}'",
".",
"format",
"(",
"interval",
")",
")",
"# get the data and header for the new collection",
"new_data",
",",
"d_times",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"i",
"in",
"dates",
":",
"vals",
"=",
"data_dict",
"[",
"i",
"]",
"if",
"vals",
"!=",
"[",
"]",
":",
"new_data",
".",
"append",
"(",
"funct",
"(",
"vals",
")",
")",
"d_times",
".",
"append",
"(",
"i",
")",
"new_header",
"=",
"self",
".",
"header",
".",
"duplicate",
"(",
")",
"if",
"operation",
"==",
"'percentile'",
":",
"new_header",
".",
"metadata",
"[",
"'operation'",
"]",
"=",
"'{} percentile'",
".",
"format",
"(",
"percentile",
")",
"else",
":",
"new_header",
".",
"metadata",
"[",
"'operation'",
"]",
"=",
"operation",
"# build the final data collection",
"if",
"interval",
"==",
"'monthly'",
":",
"collection",
"=",
"MonthlyCollection",
"(",
"new_header",
",",
"new_data",
",",
"d_times",
")",
"elif",
"interval",
"==",
"'daily'",
":",
"collection",
"=",
"DailyCollection",
"(",
"new_header",
",",
"new_data",
",",
"d_times",
")",
"elif",
"interval",
"==",
"'monthlyperhour'",
":",
"collection",
"=",
"MonthlyPerHourCollection",
"(",
"new_header",
",",
"new_data",
",",
"d_times",
")",
"collection",
".",
"_validated_a_period",
"=",
"True",
"return",
"collection"
] | Get a collection of a certain time interval with a given math operation. | [
"Get",
"a",
"collection",
"of",
"a",
"certain",
"time",
"interval",
"with",
"a",
"given",
"math",
"operation",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L449-L495 | train | 237,464 |
ladybug-tools/ladybug | ladybug/datacollection.py | HourlyContinuousCollection.datetimes | def datetimes(self):
"""Return datetimes for this collection as a tuple."""
if self._datetimes is None:
self._datetimes = tuple(self.header.analysis_period.datetimes)
return self._datetimes | python | def datetimes(self):
"""Return datetimes for this collection as a tuple."""
if self._datetimes is None:
self._datetimes = tuple(self.header.analysis_period.datetimes)
return self._datetimes | [
"def",
"datetimes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_datetimes",
"is",
"None",
":",
"self",
".",
"_datetimes",
"=",
"tuple",
"(",
"self",
".",
"header",
".",
"analysis_period",
".",
"datetimes",
")",
"return",
"self",
".",
"_datetimes"
] | Return datetimes for this collection as a tuple. | [
"Return",
"datetimes",
"for",
"this",
"collection",
"as",
"a",
"tuple",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L554-L558 | train | 237,465 |
ladybug-tools/ladybug | ladybug/datacollection.py | HourlyContinuousCollection.interpolate_to_timestep | def interpolate_to_timestep(self, timestep, cumulative=None):
"""Interpolate data for a finer timestep using a linear interpolation.
Args:
timestep: Target timestep as an integer. Target timestep must be
divisable by current timestep.
cumulative: A boolean that sets whether the interpolation
should treat the data colection values as cumulative, in
which case the value at each timestep is the value over
that timestep (instead of over the hour). The default will
check the DataType to see if this type of data is typically
cumulative over time.
Return:
A continuous hourly data collection with data interpolated to
the input timestep.
"""
assert timestep % self.header.analysis_period.timestep == 0, \
'Target timestep({}) must be divisable by current timestep({})' \
.format(timestep, self.header.analysis_period.timestep)
if cumulative is not None:
assert isinstance(cumulative, bool), \
'Expected Boolean. Got {}'.format(type(cumulative))
# generate new data
_new_values = []
_data_length = len(self._values)
for d in xrange(_data_length):
for _v in self._xxrange(self[d], self[(d + 1) % _data_length], timestep):
_new_values.append(_v)
# divide cumulative values by the timestep
native_cumulative = self.header.data_type.cumulative
if cumulative is True or (cumulative is None and native_cumulative):
for i, d in enumerate(_new_values):
_new_values[i] = d / timestep
# shift data by a half-hour if data is averaged or cumulative over an hour
if self.header.data_type.point_in_time is False:
shift_dist = int(timestep / 2)
_new_values = _new_values[-shift_dist:] + _new_values[:-shift_dist]
# build a new header
a_per = self.header.analysis_period
_new_a_per = AnalysisPeriod(a_per.st_month, a_per.st_day, a_per.st_hour,
a_per.end_month, a_per.end_day, a_per.end_hour,
timestep, a_per.is_leap_year)
_new_header = self.header.duplicate()
_new_header._analysis_period = _new_a_per
return HourlyContinuousCollection(_new_header, _new_values) | python | def interpolate_to_timestep(self, timestep, cumulative=None):
"""Interpolate data for a finer timestep using a linear interpolation.
Args:
timestep: Target timestep as an integer. Target timestep must be
divisable by current timestep.
cumulative: A boolean that sets whether the interpolation
should treat the data colection values as cumulative, in
which case the value at each timestep is the value over
that timestep (instead of over the hour). The default will
check the DataType to see if this type of data is typically
cumulative over time.
Return:
A continuous hourly data collection with data interpolated to
the input timestep.
"""
assert timestep % self.header.analysis_period.timestep == 0, \
'Target timestep({}) must be divisable by current timestep({})' \
.format(timestep, self.header.analysis_period.timestep)
if cumulative is not None:
assert isinstance(cumulative, bool), \
'Expected Boolean. Got {}'.format(type(cumulative))
# generate new data
_new_values = []
_data_length = len(self._values)
for d in xrange(_data_length):
for _v in self._xxrange(self[d], self[(d + 1) % _data_length], timestep):
_new_values.append(_v)
# divide cumulative values by the timestep
native_cumulative = self.header.data_type.cumulative
if cumulative is True or (cumulative is None and native_cumulative):
for i, d in enumerate(_new_values):
_new_values[i] = d / timestep
# shift data by a half-hour if data is averaged or cumulative over an hour
if self.header.data_type.point_in_time is False:
shift_dist = int(timestep / 2)
_new_values = _new_values[-shift_dist:] + _new_values[:-shift_dist]
# build a new header
a_per = self.header.analysis_period
_new_a_per = AnalysisPeriod(a_per.st_month, a_per.st_day, a_per.st_hour,
a_per.end_month, a_per.end_day, a_per.end_hour,
timestep, a_per.is_leap_year)
_new_header = self.header.duplicate()
_new_header._analysis_period = _new_a_per
return HourlyContinuousCollection(_new_header, _new_values) | [
"def",
"interpolate_to_timestep",
"(",
"self",
",",
"timestep",
",",
"cumulative",
"=",
"None",
")",
":",
"assert",
"timestep",
"%",
"self",
".",
"header",
".",
"analysis_period",
".",
"timestep",
"==",
"0",
",",
"'Target timestep({}) must be divisable by current timestep({})'",
".",
"format",
"(",
"timestep",
",",
"self",
".",
"header",
".",
"analysis_period",
".",
"timestep",
")",
"if",
"cumulative",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(",
"cumulative",
",",
"bool",
")",
",",
"'Expected Boolean. Got {}'",
".",
"format",
"(",
"type",
"(",
"cumulative",
")",
")",
"# generate new data",
"_new_values",
"=",
"[",
"]",
"_data_length",
"=",
"len",
"(",
"self",
".",
"_values",
")",
"for",
"d",
"in",
"xrange",
"(",
"_data_length",
")",
":",
"for",
"_v",
"in",
"self",
".",
"_xxrange",
"(",
"self",
"[",
"d",
"]",
",",
"self",
"[",
"(",
"d",
"+",
"1",
")",
"%",
"_data_length",
"]",
",",
"timestep",
")",
":",
"_new_values",
".",
"append",
"(",
"_v",
")",
"# divide cumulative values by the timestep",
"native_cumulative",
"=",
"self",
".",
"header",
".",
"data_type",
".",
"cumulative",
"if",
"cumulative",
"is",
"True",
"or",
"(",
"cumulative",
"is",
"None",
"and",
"native_cumulative",
")",
":",
"for",
"i",
",",
"d",
"in",
"enumerate",
"(",
"_new_values",
")",
":",
"_new_values",
"[",
"i",
"]",
"=",
"d",
"/",
"timestep",
"# shift data by a half-hour if data is averaged or cumulative over an hour",
"if",
"self",
".",
"header",
".",
"data_type",
".",
"point_in_time",
"is",
"False",
":",
"shift_dist",
"=",
"int",
"(",
"timestep",
"/",
"2",
")",
"_new_values",
"=",
"_new_values",
"[",
"-",
"shift_dist",
":",
"]",
"+",
"_new_values",
"[",
":",
"-",
"shift_dist",
"]",
"# build a new header",
"a_per",
"=",
"self",
".",
"header",
".",
"analysis_period",
"_new_a_per",
"=",
"AnalysisPeriod",
"(",
"a_per",
".",
"st_month",
",",
"a_per",
".",
"st_day",
",",
"a_per",
".",
"st_hour",
",",
"a_per",
".",
"end_month",
",",
"a_per",
".",
"end_day",
",",
"a_per",
".",
"end_hour",
",",
"timestep",
",",
"a_per",
".",
"is_leap_year",
")",
"_new_header",
"=",
"self",
".",
"header",
".",
"duplicate",
"(",
")",
"_new_header",
".",
"_analysis_period",
"=",
"_new_a_per",
"return",
"HourlyContinuousCollection",
"(",
"_new_header",
",",
"_new_values",
")"
] | Interpolate data for a finer timestep using a linear interpolation.
Args:
timestep: Target timestep as an integer. Target timestep must be
divisable by current timestep.
cumulative: A boolean that sets whether the interpolation
should treat the data colection values as cumulative, in
which case the value at each timestep is the value over
that timestep (instead of over the hour). The default will
check the DataType to see if this type of data is typically
cumulative over time.
Return:
A continuous hourly data collection with data interpolated to
the input timestep. | [
"Interpolate",
"data",
"for",
"a",
"finer",
"timestep",
"using",
"a",
"linear",
"interpolation",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L567-L616 | train | 237,466 |
ladybug-tools/ladybug | ladybug/datacollection.py | HourlyContinuousCollection.filter_by_hoys | def filter_by_hoys(self, hoys):
"""Filter the Data Collection based onva list of hoys.
Args:
hoys: A List of hours of the year 0..8759
Return:
A new Data Collection with filtered data
"""
existing_hoys = self.header.analysis_period.hoys
hoys = [h for h in hoys if h in existing_hoys]
_moys = tuple(int(hour * 60) for hour in hoys)
return self.filter_by_moys(_moys) | python | def filter_by_hoys(self, hoys):
"""Filter the Data Collection based onva list of hoys.
Args:
hoys: A List of hours of the year 0..8759
Return:
A new Data Collection with filtered data
"""
existing_hoys = self.header.analysis_period.hoys
hoys = [h for h in hoys if h in existing_hoys]
_moys = tuple(int(hour * 60) for hour in hoys)
return self.filter_by_moys(_moys) | [
"def",
"filter_by_hoys",
"(",
"self",
",",
"hoys",
")",
":",
"existing_hoys",
"=",
"self",
".",
"header",
".",
"analysis_period",
".",
"hoys",
"hoys",
"=",
"[",
"h",
"for",
"h",
"in",
"hoys",
"if",
"h",
"in",
"existing_hoys",
"]",
"_moys",
"=",
"tuple",
"(",
"int",
"(",
"hour",
"*",
"60",
")",
"for",
"hour",
"in",
"hoys",
")",
"return",
"self",
".",
"filter_by_moys",
"(",
"_moys",
")"
] | Filter the Data Collection based onva list of hoys.
Args:
hoys: A List of hours of the year 0..8759
Return:
A new Data Collection with filtered data | [
"Filter",
"the",
"Data",
"Collection",
"based",
"onva",
"list",
"of",
"hoys",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L683-L695 | train | 237,467 |
ladybug-tools/ladybug | ladybug/datacollection.py | HourlyContinuousCollection.to_immutable | def to_immutable(self):
"""Get an immutable version of this collection."""
if self._enumeration is None:
self._get_mutable_enumeration()
col_obj = self._enumeration['immutable'][self._collection_type]
return col_obj(self.header, self.values) | python | def to_immutable(self):
"""Get an immutable version of this collection."""
if self._enumeration is None:
self._get_mutable_enumeration()
col_obj = self._enumeration['immutable'][self._collection_type]
return col_obj(self.header, self.values) | [
"def",
"to_immutable",
"(",
"self",
")",
":",
"if",
"self",
".",
"_enumeration",
"is",
"None",
":",
"self",
".",
"_get_mutable_enumeration",
"(",
")",
"col_obj",
"=",
"self",
".",
"_enumeration",
"[",
"'immutable'",
"]",
"[",
"self",
".",
"_collection_type",
"]",
"return",
"col_obj",
"(",
"self",
".",
"header",
",",
"self",
".",
"values",
")"
] | Get an immutable version of this collection. | [
"Get",
"an",
"immutable",
"version",
"of",
"this",
"collection",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L782-L787 | train | 237,468 |
ladybug-tools/ladybug | ladybug/datacollection.py | HourlyContinuousCollection.to_discontinuous | def to_discontinuous(self):
"""Return a discontinuous version of the current collection."""
collection = HourlyDiscontinuousCollection(self.header.duplicate(),
self.values, self.datetimes)
collection._validated_a_period = True
return collection | python | def to_discontinuous(self):
"""Return a discontinuous version of the current collection."""
collection = HourlyDiscontinuousCollection(self.header.duplicate(),
self.values, self.datetimes)
collection._validated_a_period = True
return collection | [
"def",
"to_discontinuous",
"(",
"self",
")",
":",
"collection",
"=",
"HourlyDiscontinuousCollection",
"(",
"self",
".",
"header",
".",
"duplicate",
"(",
")",
",",
"self",
".",
"values",
",",
"self",
".",
"datetimes",
")",
"collection",
".",
"_validated_a_period",
"=",
"True",
"return",
"collection"
] | Return a discontinuous version of the current collection. | [
"Return",
"a",
"discontinuous",
"version",
"of",
"the",
"current",
"collection",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L854-L859 | train | 237,469 |
ladybug-tools/ladybug | ladybug/datacollection.py | HourlyContinuousCollection._get_analysis_period_subset | def _get_analysis_period_subset(self, a_per):
"""Return an analysis_period is always a subset of the Data Collection"""
if self.header.analysis_period.is_annual:
return a_per
new_needed = False
n_ap = [a_per.st_month, a_per.st_day, a_per.st_hour,
a_per.end_month, a_per.end_day, a_per.end_hour,
a_per.timestep, a_per.is_leap_year]
if a_per.st_hour < self.header.analysis_period.st_hour:
n_ap[2] = self.header.analysis_period.st_hour
new_needed = True
if a_per.end_hour > self.header.analysis_period.end_hour:
n_ap[5] = self.header.analysis_period.end_hour
new_needed = True
if a_per.st_time.doy < self.header.analysis_period.st_time.doy:
n_ap[0] = self.header.analysis_period.st_month
n_ap[1] = self.header.analysis_period.st_day
new_needed = True
if a_per.end_time.doy > self.header.analysis_period.end_time.doy:
n_ap[3] = self.header.analysis_period.end_month
n_ap[4] = self.header.analysis_period.end_day
new_needed = True
if new_needed is False:
return a_per
else:
return AnalysisPeriod(*n_ap) | python | def _get_analysis_period_subset(self, a_per):
"""Return an analysis_period is always a subset of the Data Collection"""
if self.header.analysis_period.is_annual:
return a_per
new_needed = False
n_ap = [a_per.st_month, a_per.st_day, a_per.st_hour,
a_per.end_month, a_per.end_day, a_per.end_hour,
a_per.timestep, a_per.is_leap_year]
if a_per.st_hour < self.header.analysis_period.st_hour:
n_ap[2] = self.header.analysis_period.st_hour
new_needed = True
if a_per.end_hour > self.header.analysis_period.end_hour:
n_ap[5] = self.header.analysis_period.end_hour
new_needed = True
if a_per.st_time.doy < self.header.analysis_period.st_time.doy:
n_ap[0] = self.header.analysis_period.st_month
n_ap[1] = self.header.analysis_period.st_day
new_needed = True
if a_per.end_time.doy > self.header.analysis_period.end_time.doy:
n_ap[3] = self.header.analysis_period.end_month
n_ap[4] = self.header.analysis_period.end_day
new_needed = True
if new_needed is False:
return a_per
else:
return AnalysisPeriod(*n_ap) | [
"def",
"_get_analysis_period_subset",
"(",
"self",
",",
"a_per",
")",
":",
"if",
"self",
".",
"header",
".",
"analysis_period",
".",
"is_annual",
":",
"return",
"a_per",
"new_needed",
"=",
"False",
"n_ap",
"=",
"[",
"a_per",
".",
"st_month",
",",
"a_per",
".",
"st_day",
",",
"a_per",
".",
"st_hour",
",",
"a_per",
".",
"end_month",
",",
"a_per",
".",
"end_day",
",",
"a_per",
".",
"end_hour",
",",
"a_per",
".",
"timestep",
",",
"a_per",
".",
"is_leap_year",
"]",
"if",
"a_per",
".",
"st_hour",
"<",
"self",
".",
"header",
".",
"analysis_period",
".",
"st_hour",
":",
"n_ap",
"[",
"2",
"]",
"=",
"self",
".",
"header",
".",
"analysis_period",
".",
"st_hour",
"new_needed",
"=",
"True",
"if",
"a_per",
".",
"end_hour",
">",
"self",
".",
"header",
".",
"analysis_period",
".",
"end_hour",
":",
"n_ap",
"[",
"5",
"]",
"=",
"self",
".",
"header",
".",
"analysis_period",
".",
"end_hour",
"new_needed",
"=",
"True",
"if",
"a_per",
".",
"st_time",
".",
"doy",
"<",
"self",
".",
"header",
".",
"analysis_period",
".",
"st_time",
".",
"doy",
":",
"n_ap",
"[",
"0",
"]",
"=",
"self",
".",
"header",
".",
"analysis_period",
".",
"st_month",
"n_ap",
"[",
"1",
"]",
"=",
"self",
".",
"header",
".",
"analysis_period",
".",
"st_day",
"new_needed",
"=",
"True",
"if",
"a_per",
".",
"end_time",
".",
"doy",
">",
"self",
".",
"header",
".",
"analysis_period",
".",
"end_time",
".",
"doy",
":",
"n_ap",
"[",
"3",
"]",
"=",
"self",
".",
"header",
".",
"analysis_period",
".",
"end_month",
"n_ap",
"[",
"4",
"]",
"=",
"self",
".",
"header",
".",
"analysis_period",
".",
"end_day",
"new_needed",
"=",
"True",
"if",
"new_needed",
"is",
"False",
":",
"return",
"a_per",
"else",
":",
"return",
"AnalysisPeriod",
"(",
"*",
"n_ap",
")"
] | Return an analysis_period is always a subset of the Data Collection | [
"Return",
"an",
"analysis_period",
"is",
"always",
"a",
"subset",
"of",
"the",
"Data",
"Collection"
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L875-L901 | train | 237,470 |
ladybug-tools/ladybug | ladybug/datacollection.py | DailyCollection._monthly_operation | def _monthly_operation(self, operation, percentile=0):
"""Get a MonthlyCollection given a certain operation."""
# Retrive the correct operation.
if operation == 'average':
funct = self._average
elif operation == 'total':
funct = self._total
else:
assert 0 <= percentile <= 100, \
'percentile must be between 0 and 100. Got {}'.format(percentile)
funct = self._get_percentile_function(percentile)
# Get the data for the new collection
data_dict = self.group_by_month()
new_data, d_times = [], []
for i in self.header.analysis_period.months_int:
vals = data_dict[i]
if vals != []:
new_data.append(funct(vals))
d_times.append(i)
# build the new monthly collection
new_header = self.header.duplicate()
if operation == 'percentile':
new_header.metadata['operation'] = '{} percentile'.format(percentile)
else:
new_header.metadata['operation'] = operation
collection = MonthlyCollection(new_header, new_data, d_times)
collection._validated_a_period = True
return collection | python | def _monthly_operation(self, operation, percentile=0):
"""Get a MonthlyCollection given a certain operation."""
# Retrive the correct operation.
if operation == 'average':
funct = self._average
elif operation == 'total':
funct = self._total
else:
assert 0 <= percentile <= 100, \
'percentile must be between 0 and 100. Got {}'.format(percentile)
funct = self._get_percentile_function(percentile)
# Get the data for the new collection
data_dict = self.group_by_month()
new_data, d_times = [], []
for i in self.header.analysis_period.months_int:
vals = data_dict[i]
if vals != []:
new_data.append(funct(vals))
d_times.append(i)
# build the new monthly collection
new_header = self.header.duplicate()
if operation == 'percentile':
new_header.metadata['operation'] = '{} percentile'.format(percentile)
else:
new_header.metadata['operation'] = operation
collection = MonthlyCollection(new_header, new_data, d_times)
collection._validated_a_period = True
return collection | [
"def",
"_monthly_operation",
"(",
"self",
",",
"operation",
",",
"percentile",
"=",
"0",
")",
":",
"# Retrive the correct operation.",
"if",
"operation",
"==",
"'average'",
":",
"funct",
"=",
"self",
".",
"_average",
"elif",
"operation",
"==",
"'total'",
":",
"funct",
"=",
"self",
".",
"_total",
"else",
":",
"assert",
"0",
"<=",
"percentile",
"<=",
"100",
",",
"'percentile must be between 0 and 100. Got {}'",
".",
"format",
"(",
"percentile",
")",
"funct",
"=",
"self",
".",
"_get_percentile_function",
"(",
"percentile",
")",
"# Get the data for the new collection",
"data_dict",
"=",
"self",
".",
"group_by_month",
"(",
")",
"new_data",
",",
"d_times",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"i",
"in",
"self",
".",
"header",
".",
"analysis_period",
".",
"months_int",
":",
"vals",
"=",
"data_dict",
"[",
"i",
"]",
"if",
"vals",
"!=",
"[",
"]",
":",
"new_data",
".",
"append",
"(",
"funct",
"(",
"vals",
")",
")",
"d_times",
".",
"append",
"(",
"i",
")",
"# build the new monthly collection",
"new_header",
"=",
"self",
".",
"header",
".",
"duplicate",
"(",
")",
"if",
"operation",
"==",
"'percentile'",
":",
"new_header",
".",
"metadata",
"[",
"'operation'",
"]",
"=",
"'{} percentile'",
".",
"format",
"(",
"percentile",
")",
"else",
":",
"new_header",
".",
"metadata",
"[",
"'operation'",
"]",
"=",
"operation",
"collection",
"=",
"MonthlyCollection",
"(",
"new_header",
",",
"new_data",
",",
"d_times",
")",
"collection",
".",
"_validated_a_period",
"=",
"True",
"return",
"collection"
] | Get a MonthlyCollection given a certain operation. | [
"Get",
"a",
"MonthlyCollection",
"given",
"a",
"certain",
"operation",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L1095-L1124 | train | 237,471 |
ladybug-tools/ladybug | ladybug/datatype/temperaturetime.py | TemperatureTime.to_unit | def to_unit(self, values, unit, from_unit):
"""Return values converted to the unit given the input from_unit."""
return self._to_unit_base('degC-days', values, unit, from_unit) | python | def to_unit(self, values, unit, from_unit):
"""Return values converted to the unit given the input from_unit."""
return self._to_unit_base('degC-days', values, unit, from_unit) | [
"def",
"to_unit",
"(",
"self",
",",
"values",
",",
"unit",
",",
"from_unit",
")",
":",
"return",
"self",
".",
"_to_unit_base",
"(",
"'degC-days'",
",",
"values",
",",
"unit",
",",
"from_unit",
")"
] | Return values converted to the unit given the input from_unit. | [
"Return",
"values",
"converted",
"to",
"the",
"unit",
"given",
"the",
"input",
"from_unit",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datatype/temperaturetime.py#L33-L35 | train | 237,472 |
ladybug-tools/ladybug | ladybug/rootfind.py | bisect | def bisect(a, b, fn, epsilon, target):
"""
The simplest root-finding algorithm.
It is extremely reliable. However, it converges slowly for this reason,
it is recommended that this only be used after the secant() method has
returned None.
Args:
a: A lower guess of the value you are tying to find.
b: A higher guess of the value you are tying to find.
fn: A function representing the relationship between the value you are
trying to find and the target condition you are trying to satisfy.
It should typically be structured in the following way:
`def fn(value_trying_to_find):
funct(value_trying_to_find) - target_desired_from_funct`
...but the subtraction should be swtiched if value_trying_to_find
has a negative relationship with the funct.
epsilon: The acceptable error in the target_desired_from_funct.
target: The target slope (typically 0 for a local minima or maxima).
Returns:
root: The value that gives the target_desired_from_funct.
References
----------
[1] Wikipedia contributors. (2018, December 29). Root-finding algorithm.
In Wikipedia, The Free Encyclopedia. Retrieved 18:16, December 30, 2018,
from https://en.wikipedia.org/wiki/Root-finding_algorithm#Bisection_method
"""
while (abs(b - a) > 2 * epsilon):
midpoint = (b + a) / 2
a_t = fn(a)
b_t = fn(b)
midpoint_t = fn(midpoint)
if (a_t - target) * (midpoint_t - target) < 0:
b = midpoint
elif (b_t - target) * (midpoint_t - target) < 0:
a = midpoint
else:
return -999
return midpoint | python | def bisect(a, b, fn, epsilon, target):
"""
The simplest root-finding algorithm.
It is extremely reliable. However, it converges slowly for this reason,
it is recommended that this only be used after the secant() method has
returned None.
Args:
a: A lower guess of the value you are tying to find.
b: A higher guess of the value you are tying to find.
fn: A function representing the relationship between the value you are
trying to find and the target condition you are trying to satisfy.
It should typically be structured in the following way:
`def fn(value_trying_to_find):
funct(value_trying_to_find) - target_desired_from_funct`
...but the subtraction should be swtiched if value_trying_to_find
has a negative relationship with the funct.
epsilon: The acceptable error in the target_desired_from_funct.
target: The target slope (typically 0 for a local minima or maxima).
Returns:
root: The value that gives the target_desired_from_funct.
References
----------
[1] Wikipedia contributors. (2018, December 29). Root-finding algorithm.
In Wikipedia, The Free Encyclopedia. Retrieved 18:16, December 30, 2018,
from https://en.wikipedia.org/wiki/Root-finding_algorithm#Bisection_method
"""
while (abs(b - a) > 2 * epsilon):
midpoint = (b + a) / 2
a_t = fn(a)
b_t = fn(b)
midpoint_t = fn(midpoint)
if (a_t - target) * (midpoint_t - target) < 0:
b = midpoint
elif (b_t - target) * (midpoint_t - target) < 0:
a = midpoint
else:
return -999
return midpoint | [
"def",
"bisect",
"(",
"a",
",",
"b",
",",
"fn",
",",
"epsilon",
",",
"target",
")",
":",
"while",
"(",
"abs",
"(",
"b",
"-",
"a",
")",
">",
"2",
"*",
"epsilon",
")",
":",
"midpoint",
"=",
"(",
"b",
"+",
"a",
")",
"/",
"2",
"a_t",
"=",
"fn",
"(",
"a",
")",
"b_t",
"=",
"fn",
"(",
"b",
")",
"midpoint_t",
"=",
"fn",
"(",
"midpoint",
")",
"if",
"(",
"a_t",
"-",
"target",
")",
"*",
"(",
"midpoint_t",
"-",
"target",
")",
"<",
"0",
":",
"b",
"=",
"midpoint",
"elif",
"(",
"b_t",
"-",
"target",
")",
"*",
"(",
"midpoint_t",
"-",
"target",
")",
"<",
"0",
":",
"a",
"=",
"midpoint",
"else",
":",
"return",
"-",
"999",
"return",
"midpoint"
] | The simplest root-finding algorithm.
It is extremely reliable. However, it converges slowly for this reason,
it is recommended that this only be used after the secant() method has
returned None.
Args:
a: A lower guess of the value you are tying to find.
b: A higher guess of the value you are tying to find.
fn: A function representing the relationship between the value you are
trying to find and the target condition you are trying to satisfy.
It should typically be structured in the following way:
`def fn(value_trying_to_find):
funct(value_trying_to_find) - target_desired_from_funct`
...but the subtraction should be swtiched if value_trying_to_find
has a negative relationship with the funct.
epsilon: The acceptable error in the target_desired_from_funct.
target: The target slope (typically 0 for a local minima or maxima).
Returns:
root: The value that gives the target_desired_from_funct.
References
----------
[1] Wikipedia contributors. (2018, December 29). Root-finding algorithm.
In Wikipedia, The Free Encyclopedia. Retrieved 18:16, December 30, 2018,
from https://en.wikipedia.org/wiki/Root-finding_algorithm#Bisection_method | [
"The",
"simplest",
"root",
"-",
"finding",
"algorithm",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/rootfind.py#L56-L98 | train | 237,473 |
ladybug-tools/ladybug | ladybug/location.py | Location.from_json | def from_json(cls, data):
"""Create a location from a dictionary.
Args:
data: {
"city": "-",
"latitude": 0,
"longitude": 0,
"time_zone": 0,
"elevation": 0}
"""
optional_keys = ('city', 'state', 'country', 'latitude', 'longitude',
'time_zone', 'elevation', 'station_id', 'source')
for key in optional_keys:
if key not in data:
data[key] = None
return cls(data['city'], data['state'], data['country'], data['latitude'],
data['longitude'], data['time_zone'], data['elevation'],
data['station_id'], data['source']) | python | def from_json(cls, data):
"""Create a location from a dictionary.
Args:
data: {
"city": "-",
"latitude": 0,
"longitude": 0,
"time_zone": 0,
"elevation": 0}
"""
optional_keys = ('city', 'state', 'country', 'latitude', 'longitude',
'time_zone', 'elevation', 'station_id', 'source')
for key in optional_keys:
if key not in data:
data[key] = None
return cls(data['city'], data['state'], data['country'], data['latitude'],
data['longitude'], data['time_zone'], data['elevation'],
data['station_id'], data['source']) | [
"def",
"from_json",
"(",
"cls",
",",
"data",
")",
":",
"optional_keys",
"=",
"(",
"'city'",
",",
"'state'",
",",
"'country'",
",",
"'latitude'",
",",
"'longitude'",
",",
"'time_zone'",
",",
"'elevation'",
",",
"'station_id'",
",",
"'source'",
")",
"for",
"key",
"in",
"optional_keys",
":",
"if",
"key",
"not",
"in",
"data",
":",
"data",
"[",
"key",
"]",
"=",
"None",
"return",
"cls",
"(",
"data",
"[",
"'city'",
"]",
",",
"data",
"[",
"'state'",
"]",
",",
"data",
"[",
"'country'",
"]",
",",
"data",
"[",
"'latitude'",
"]",
",",
"data",
"[",
"'longitude'",
"]",
",",
"data",
"[",
"'time_zone'",
"]",
",",
"data",
"[",
"'elevation'",
"]",
",",
"data",
"[",
"'station_id'",
"]",
",",
"data",
"[",
"'source'",
"]",
")"
] | Create a location from a dictionary.
Args:
data: {
"city": "-",
"latitude": 0,
"longitude": 0,
"time_zone": 0,
"elevation": 0} | [
"Create",
"a",
"location",
"from",
"a",
"dictionary",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/location.py#L40-L59 | train | 237,474 |
ladybug-tools/ladybug | ladybug/location.py | Location.from_location | def from_location(cls, location):
"""Try to create a Ladybug location from a location string.
Args:
locationString: Location string
Usage:
l = Location.from_location(locationString)
"""
if not location:
return cls()
try:
if hasattr(location, 'isLocation'):
# Ladybug location
return location
elif hasattr(location, 'Latitude'):
# Revit's location
return cls(city=str(location.Name.replace(",", " ")),
latitude=location.Latitude,
longitude=location.Longitude)
elif location.startswith('Site:'):
loc, city, latitude, longitude, time_zone, elevation = \
[x.strip() for x in re.findall(r'\r*\n*([^\r\n]*)[,|;]',
location, re.DOTALL)]
else:
try:
city, latitude, longitude, time_zone, elevation = \
[key.split(":")[-1].strip()
for key in location.split(",")]
except ValueError:
# it's just the city name
return cls(city=location)
return cls(city=city, country=None, latitude=latitude,
longitude=longitude, time_zone=time_zone,
elevation=elevation)
except Exception as e:
raise ValueError(
"Failed to create a Location from %s!\n%s" % (location, e)) | python | def from_location(cls, location):
"""Try to create a Ladybug location from a location string.
Args:
locationString: Location string
Usage:
l = Location.from_location(locationString)
"""
if not location:
return cls()
try:
if hasattr(location, 'isLocation'):
# Ladybug location
return location
elif hasattr(location, 'Latitude'):
# Revit's location
return cls(city=str(location.Name.replace(",", " ")),
latitude=location.Latitude,
longitude=location.Longitude)
elif location.startswith('Site:'):
loc, city, latitude, longitude, time_zone, elevation = \
[x.strip() for x in re.findall(r'\r*\n*([^\r\n]*)[,|;]',
location, re.DOTALL)]
else:
try:
city, latitude, longitude, time_zone, elevation = \
[key.split(":")[-1].strip()
for key in location.split(",")]
except ValueError:
# it's just the city name
return cls(city=location)
return cls(city=city, country=None, latitude=latitude,
longitude=longitude, time_zone=time_zone,
elevation=elevation)
except Exception as e:
raise ValueError(
"Failed to create a Location from %s!\n%s" % (location, e)) | [
"def",
"from_location",
"(",
"cls",
",",
"location",
")",
":",
"if",
"not",
"location",
":",
"return",
"cls",
"(",
")",
"try",
":",
"if",
"hasattr",
"(",
"location",
",",
"'isLocation'",
")",
":",
"# Ladybug location",
"return",
"location",
"elif",
"hasattr",
"(",
"location",
",",
"'Latitude'",
")",
":",
"# Revit's location",
"return",
"cls",
"(",
"city",
"=",
"str",
"(",
"location",
".",
"Name",
".",
"replace",
"(",
"\",\"",
",",
"\" \"",
")",
")",
",",
"latitude",
"=",
"location",
".",
"Latitude",
",",
"longitude",
"=",
"location",
".",
"Longitude",
")",
"elif",
"location",
".",
"startswith",
"(",
"'Site:'",
")",
":",
"loc",
",",
"city",
",",
"latitude",
",",
"longitude",
",",
"time_zone",
",",
"elevation",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"re",
".",
"findall",
"(",
"r'\\r*\\n*([^\\r\\n]*)[,|;]'",
",",
"location",
",",
"re",
".",
"DOTALL",
")",
"]",
"else",
":",
"try",
":",
"city",
",",
"latitude",
",",
"longitude",
",",
"time_zone",
",",
"elevation",
"=",
"[",
"key",
".",
"split",
"(",
"\":\"",
")",
"[",
"-",
"1",
"]",
".",
"strip",
"(",
")",
"for",
"key",
"in",
"location",
".",
"split",
"(",
"\",\"",
")",
"]",
"except",
"ValueError",
":",
"# it's just the city name",
"return",
"cls",
"(",
"city",
"=",
"location",
")",
"return",
"cls",
"(",
"city",
"=",
"city",
",",
"country",
"=",
"None",
",",
"latitude",
"=",
"latitude",
",",
"longitude",
"=",
"longitude",
",",
"time_zone",
"=",
"time_zone",
",",
"elevation",
"=",
"elevation",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"ValueError",
"(",
"\"Failed to create a Location from %s!\\n%s\"",
"%",
"(",
"location",
",",
"e",
")",
")"
] | Try to create a Ladybug location from a location string.
Args:
locationString: Location string
Usage:
l = Location.from_location(locationString) | [
"Try",
"to",
"create",
"a",
"Ladybug",
"location",
"from",
"a",
"location",
"string",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/location.py#L62-L104 | train | 237,475 |
ladybug-tools/ladybug | ladybug/location.py | Location.duplicate | def duplicate(self):
"""Duplicate location."""
return Location(self.city, self.state, self.country,
self.latitude, self.longitude, self.time_zone, self.elevation,
self.station_id, self.source) | python | def duplicate(self):
"""Duplicate location."""
return Location(self.city, self.state, self.country,
self.latitude, self.longitude, self.time_zone, self.elevation,
self.station_id, self.source) | [
"def",
"duplicate",
"(",
"self",
")",
":",
"return",
"Location",
"(",
"self",
".",
"city",
",",
"self",
".",
"state",
",",
"self",
".",
"country",
",",
"self",
".",
"latitude",
",",
"self",
".",
"longitude",
",",
"self",
".",
"time_zone",
",",
"self",
".",
"elevation",
",",
"self",
".",
"station_id",
",",
"self",
".",
"source",
")"
] | Duplicate location. | [
"Duplicate",
"location",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/location.py#L158-L162 | train | 237,476 |
ladybug-tools/ladybug | ladybug/location.py | Location.ep_style_location_string | def ep_style_location_string(self):
"""Return EnergyPlus's location string."""
return "Site:Location,\n " + \
self.city + ',\n ' + \
str(self.latitude) + ', !Latitude\n ' + \
str(self.longitude) + ', !Longitude\n ' + \
str(self.time_zone) + ', !Time Zone\n ' + \
str(self.elevation) + '; !Elevation' | python | def ep_style_location_string(self):
"""Return EnergyPlus's location string."""
return "Site:Location,\n " + \
self.city + ',\n ' + \
str(self.latitude) + ', !Latitude\n ' + \
str(self.longitude) + ', !Longitude\n ' + \
str(self.time_zone) + ', !Time Zone\n ' + \
str(self.elevation) + '; !Elevation' | [
"def",
"ep_style_location_string",
"(",
"self",
")",
":",
"return",
"\"Site:Location,\\n \"",
"+",
"self",
".",
"city",
"+",
"',\\n '",
"+",
"str",
"(",
"self",
".",
"latitude",
")",
"+",
"', !Latitude\\n '",
"+",
"str",
"(",
"self",
".",
"longitude",
")",
"+",
"', !Longitude\\n '",
"+",
"str",
"(",
"self",
".",
"time_zone",
")",
"+",
"', !Time Zone\\n '",
"+",
"str",
"(",
"self",
".",
"elevation",
")",
"+",
"'; !Elevation'"
] | Return EnergyPlus's location string. | [
"Return",
"EnergyPlus",
"s",
"location",
"string",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/location.py#L165-L172 | train | 237,477 |
ladybug-tools/ladybug | ladybug/epw.py | EPW.from_missing_values | def from_missing_values(cls, is_leap_year=False):
"""Initalize an EPW object with all data missing or empty.
Note that this classmethod is intended for workflows where one plans
to set all of the data within the EPW object. The EPW file written
out from the use of this method is not simulate-abe or useful since
all hourly data slots just possess the missing value for that data
type. To obtain a EPW that is simulate-able in EnergyPlus, one must
at least set the following properties:
location
dry_bulb_temperature
dew_point_temperature
relative_humidity
atmospheric_station_pressure
direct_normal_radiation
diffuse_horizontal_radiation
wind_direction
wind_speed
total_sky_cover
opaque_sky_cover or horizontal_infrared_radiation_intensity
Args:
is_leap_year: A boolean to set whether the EPW object is for a leap year.
Usage:
from ladybug.epw import EPW
from ladybug.location import Location
epw = EPW.from_missing_values()
epw.location = Location('Denver Golden','CO','USA',39.74,-105.18,-7.0,1829.0)
epw.dry_bulb_temperature.values = [20] * 8760
"""
# Initialize the class with all data missing
epw_obj = cls(None)
epw_obj._is_leap_year = is_leap_year
epw_obj._location = Location()
# create an annual analysis period
analysis_period = AnalysisPeriod(is_leap_year=is_leap_year)
# create headers and an empty list for each field in epw file
headers = []
for field_number in xrange(epw_obj._num_of_fields):
field = EPWFields.field_by_number(field_number)
header = Header(data_type=field.name, unit=field.unit,
analysis_period=analysis_period)
headers.append(header)
epw_obj._data.append([])
# fill in missing datetime values and uncertainty flags.
uncertainty = '?9?9?9?9E0?9?9?9?9?9?9?9?9?9?9?9?9?9?9?9*9*9?9?9?9'
for dt in analysis_period.datetimes:
hr = dt.hour if dt.hour != 0 else 24
epw_obj._data[0].append(dt.year)
epw_obj._data[1].append(dt.month)
epw_obj._data[2].append(dt.day)
epw_obj._data[3].append(hr)
epw_obj._data[4].append(0)
epw_obj._data[5].append(uncertainty)
# generate missing hourly data
calc_length = len(analysis_period.datetimes)
for field_number in xrange(6, epw_obj._num_of_fields):
field = EPWFields.field_by_number(field_number)
mis_val = field.missing if field.missing is not None else 0
for dt in xrange(calc_length):
epw_obj._data[field_number].append(mis_val)
# finally, build the data collection objects from the headers and data
for i in xrange(epw_obj._num_of_fields):
epw_obj._data[i] = HourlyContinuousCollection(headers[i], epw_obj._data[i])
epw_obj._is_header_loaded = True
epw_obj._is_data_loaded = True
return epw_obj | python | def from_missing_values(cls, is_leap_year=False):
"""Initalize an EPW object with all data missing or empty.
Note that this classmethod is intended for workflows where one plans
to set all of the data within the EPW object. The EPW file written
out from the use of this method is not simulate-abe or useful since
all hourly data slots just possess the missing value for that data
type. To obtain a EPW that is simulate-able in EnergyPlus, one must
at least set the following properties:
location
dry_bulb_temperature
dew_point_temperature
relative_humidity
atmospheric_station_pressure
direct_normal_radiation
diffuse_horizontal_radiation
wind_direction
wind_speed
total_sky_cover
opaque_sky_cover or horizontal_infrared_radiation_intensity
Args:
is_leap_year: A boolean to set whether the EPW object is for a leap year.
Usage:
from ladybug.epw import EPW
from ladybug.location import Location
epw = EPW.from_missing_values()
epw.location = Location('Denver Golden','CO','USA',39.74,-105.18,-7.0,1829.0)
epw.dry_bulb_temperature.values = [20] * 8760
"""
# Initialize the class with all data missing
epw_obj = cls(None)
epw_obj._is_leap_year = is_leap_year
epw_obj._location = Location()
# create an annual analysis period
analysis_period = AnalysisPeriod(is_leap_year=is_leap_year)
# create headers and an empty list for each field in epw file
headers = []
for field_number in xrange(epw_obj._num_of_fields):
field = EPWFields.field_by_number(field_number)
header = Header(data_type=field.name, unit=field.unit,
analysis_period=analysis_period)
headers.append(header)
epw_obj._data.append([])
# fill in missing datetime values and uncertainty flags.
uncertainty = '?9?9?9?9E0?9?9?9?9?9?9?9?9?9?9?9?9?9?9?9*9*9?9?9?9'
for dt in analysis_period.datetimes:
hr = dt.hour if dt.hour != 0 else 24
epw_obj._data[0].append(dt.year)
epw_obj._data[1].append(dt.month)
epw_obj._data[2].append(dt.day)
epw_obj._data[3].append(hr)
epw_obj._data[4].append(0)
epw_obj._data[5].append(uncertainty)
# generate missing hourly data
calc_length = len(analysis_period.datetimes)
for field_number in xrange(6, epw_obj._num_of_fields):
field = EPWFields.field_by_number(field_number)
mis_val = field.missing if field.missing is not None else 0
for dt in xrange(calc_length):
epw_obj._data[field_number].append(mis_val)
# finally, build the data collection objects from the headers and data
for i in xrange(epw_obj._num_of_fields):
epw_obj._data[i] = HourlyContinuousCollection(headers[i], epw_obj._data[i])
epw_obj._is_header_loaded = True
epw_obj._is_data_loaded = True
return epw_obj | [
"def",
"from_missing_values",
"(",
"cls",
",",
"is_leap_year",
"=",
"False",
")",
":",
"# Initialize the class with all data missing",
"epw_obj",
"=",
"cls",
"(",
"None",
")",
"epw_obj",
".",
"_is_leap_year",
"=",
"is_leap_year",
"epw_obj",
".",
"_location",
"=",
"Location",
"(",
")",
"# create an annual analysis period",
"analysis_period",
"=",
"AnalysisPeriod",
"(",
"is_leap_year",
"=",
"is_leap_year",
")",
"# create headers and an empty list for each field in epw file",
"headers",
"=",
"[",
"]",
"for",
"field_number",
"in",
"xrange",
"(",
"epw_obj",
".",
"_num_of_fields",
")",
":",
"field",
"=",
"EPWFields",
".",
"field_by_number",
"(",
"field_number",
")",
"header",
"=",
"Header",
"(",
"data_type",
"=",
"field",
".",
"name",
",",
"unit",
"=",
"field",
".",
"unit",
",",
"analysis_period",
"=",
"analysis_period",
")",
"headers",
".",
"append",
"(",
"header",
")",
"epw_obj",
".",
"_data",
".",
"append",
"(",
"[",
"]",
")",
"# fill in missing datetime values and uncertainty flags.",
"uncertainty",
"=",
"'?9?9?9?9E0?9?9?9?9?9?9?9?9?9?9?9?9?9?9?9*9*9?9?9?9'",
"for",
"dt",
"in",
"analysis_period",
".",
"datetimes",
":",
"hr",
"=",
"dt",
".",
"hour",
"if",
"dt",
".",
"hour",
"!=",
"0",
"else",
"24",
"epw_obj",
".",
"_data",
"[",
"0",
"]",
".",
"append",
"(",
"dt",
".",
"year",
")",
"epw_obj",
".",
"_data",
"[",
"1",
"]",
".",
"append",
"(",
"dt",
".",
"month",
")",
"epw_obj",
".",
"_data",
"[",
"2",
"]",
".",
"append",
"(",
"dt",
".",
"day",
")",
"epw_obj",
".",
"_data",
"[",
"3",
"]",
".",
"append",
"(",
"hr",
")",
"epw_obj",
".",
"_data",
"[",
"4",
"]",
".",
"append",
"(",
"0",
")",
"epw_obj",
".",
"_data",
"[",
"5",
"]",
".",
"append",
"(",
"uncertainty",
")",
"# generate missing hourly data",
"calc_length",
"=",
"len",
"(",
"analysis_period",
".",
"datetimes",
")",
"for",
"field_number",
"in",
"xrange",
"(",
"6",
",",
"epw_obj",
".",
"_num_of_fields",
")",
":",
"field",
"=",
"EPWFields",
".",
"field_by_number",
"(",
"field_number",
")",
"mis_val",
"=",
"field",
".",
"missing",
"if",
"field",
".",
"missing",
"is",
"not",
"None",
"else",
"0",
"for",
"dt",
"in",
"xrange",
"(",
"calc_length",
")",
":",
"epw_obj",
".",
"_data",
"[",
"field_number",
"]",
".",
"append",
"(",
"mis_val",
")",
"# finally, build the data collection objects from the headers and data",
"for",
"i",
"in",
"xrange",
"(",
"epw_obj",
".",
"_num_of_fields",
")",
":",
"epw_obj",
".",
"_data",
"[",
"i",
"]",
"=",
"HourlyContinuousCollection",
"(",
"headers",
"[",
"i",
"]",
",",
"epw_obj",
".",
"_data",
"[",
"i",
"]",
")",
"epw_obj",
".",
"_is_header_loaded",
"=",
"True",
"epw_obj",
".",
"_is_data_loaded",
"=",
"True",
"return",
"epw_obj"
] | Initalize an EPW object with all data missing or empty.
Note that this classmethod is intended for workflows where one plans
to set all of the data within the EPW object. The EPW file written
out from the use of this method is not simulate-abe or useful since
all hourly data slots just possess the missing value for that data
type. To obtain a EPW that is simulate-able in EnergyPlus, one must
at least set the following properties:
location
dry_bulb_temperature
dew_point_temperature
relative_humidity
atmospheric_station_pressure
direct_normal_radiation
diffuse_horizontal_radiation
wind_direction
wind_speed
total_sky_cover
opaque_sky_cover or horizontal_infrared_radiation_intensity
Args:
is_leap_year: A boolean to set whether the EPW object is for a leap year.
Usage:
from ladybug.epw import EPW
from ladybug.location import Location
epw = EPW.from_missing_values()
epw.location = Location('Denver Golden','CO','USA',39.74,-105.18,-7.0,1829.0)
epw.dry_bulb_temperature.values = [20] * 8760 | [
"Initalize",
"an",
"EPW",
"object",
"with",
"all",
"data",
"missing",
"or",
"empty",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L105-L178 | train | 237,478 |
ladybug-tools/ladybug | ladybug/epw.py | EPW.from_json | def from_json(cls, data):
""" Create EPW from json dictionary.
Args:
data: {
"location": {} , // ladybug location schema
"data_collections": [], // list of hourly annual hourly data collection
schemas for each of the 35 fields within the EPW file.
"metadata": {}, // dict of metadata assigned to all data collections
"heating_dict": {}, // dict containing heating design conditions
"cooling_dict": {}, // dict containing cooling design conditions
"extremes_dict": {}, // dict containing extreme design conditions
"extreme_hot_weeks": {}, // dict with values of week-long ladybug
analysis period schemas signifying extreme hot weeks.
"extreme_cold_weeks": {}, // dict with values of week-long ladybug
analysis period schemas signifying extreme cold weeks.
"typical_weeks": {}, // dict with values of week-long ladybug
analysis period schemas signifying typical weeks.
"monthly_ground_temps": {}, // dict with keys as floats signifying
depths in meters below ground and values of monthly collection schema
"is_ip": Boolean // denote whether the data is in IP units
"is_leap_year": Boolean, // denote whether data is for a leap year
"daylight_savings_start": 0, // signify when daylight savings starts
or 0 for no daylight savings
"daylight_savings_end" 0, // signify when daylight savings ends
or 0 for no daylight savings
"comments_1": String, // epw comments
"comments_2": String // epw comments
}
"""
# Initialize the class with all data missing
epw_obj = cls(None)
epw_obj._is_header_loaded = True
epw_obj._is_data_loaded = True
# Check required and optional keys
required_keys = ('location', 'data_collections')
option_keys_dict = ('metadata', 'heating_dict', 'cooling_dict',
'extremes_dict', 'extreme_hot_weeks', 'extreme_cold_weeks',
'typical_weeks', 'monthly_ground_temps')
for key in required_keys:
assert key in data, 'Required key "{}" is missing!'.format(key)
assert len(data['data_collections']) == epw_obj._num_of_fields, \
'The number of data_collections must be {}. Got {}.'.format(
epw_obj._num_of_fields, len(data['data_collections']))
for key in option_keys_dict:
if key not in data:
data[key] = {}
# Set the required properties of the EPW object.
epw_obj._location = Location.from_json(data['location'])
epw_obj._data = [HourlyContinuousCollection.from_json(dc)
for dc in data['data_collections']]
if 'is_leap_year' in data:
epw_obj._is_leap_year = data['is_leap_year']
if 'is_ip' in data:
epw_obj._is_ip = data['is_ip']
# Check that the required properties all make sense.
for dc in epw_obj._data:
assert isinstance(dc, HourlyContinuousCollection), 'data_collections must ' \
'be of HourlyContinuousCollection schema. Got {}'.format(type(dc))
assert dc.header.analysis_period.is_annual, 'data_collections ' \
'analysis_period must be annual.'
assert dc.header.analysis_period.is_leap_year == epw_obj._is_leap_year, \
'data_collections is_leap_year is not aligned with that of the EPW.'
# Set all of the header properties if they exist in the dictionary.
epw_obj._metadata = data['metadata']
epw_obj.heating_design_condition_dictionary = data['heating_dict']
epw_obj.cooling_design_condition_dictionary = data['cooling_dict']
epw_obj.extreme_design_condition_dictionary = data['extremes_dict']
def _dejson(parent_dict, obj):
new_dict = {}
for key, val in parent_dict.items():
new_dict[key] = obj.from_json(val)
return new_dict
epw_obj.extreme_hot_weeks = _dejson(data['extreme_hot_weeks'], AnalysisPeriod)
epw_obj.extreme_cold_weeks = _dejson(data['extreme_cold_weeks'], AnalysisPeriod)
epw_obj.typical_weeks = _dejson(data['typical_weeks'], AnalysisPeriod)
epw_obj.monthly_ground_temperature = _dejson(
data['monthly_ground_temps'], MonthlyCollection)
if 'daylight_savings_start' in data:
epw_obj.daylight_savings_start = data['daylight_savings_start']
if 'daylight_savings_end' in data:
epw_obj.daylight_savings_end = data['daylight_savings_end']
if 'comments_1' in data:
epw_obj.comments_1 = data['comments_1']
if 'comments_2' in data:
epw_obj.comments_2 = data['comments_2']
return epw_obj | python | def from_json(cls, data):
""" Create EPW from json dictionary.
Args:
data: {
"location": {} , // ladybug location schema
"data_collections": [], // list of hourly annual hourly data collection
schemas for each of the 35 fields within the EPW file.
"metadata": {}, // dict of metadata assigned to all data collections
"heating_dict": {}, // dict containing heating design conditions
"cooling_dict": {}, // dict containing cooling design conditions
"extremes_dict": {}, // dict containing extreme design conditions
"extreme_hot_weeks": {}, // dict with values of week-long ladybug
analysis period schemas signifying extreme hot weeks.
"extreme_cold_weeks": {}, // dict with values of week-long ladybug
analysis period schemas signifying extreme cold weeks.
"typical_weeks": {}, // dict with values of week-long ladybug
analysis period schemas signifying typical weeks.
"monthly_ground_temps": {}, // dict with keys as floats signifying
depths in meters below ground and values of monthly collection schema
"is_ip": Boolean // denote whether the data is in IP units
"is_leap_year": Boolean, // denote whether data is for a leap year
"daylight_savings_start": 0, // signify when daylight savings starts
or 0 for no daylight savings
"daylight_savings_end" 0, // signify when daylight savings ends
or 0 for no daylight savings
"comments_1": String, // epw comments
"comments_2": String // epw comments
}
"""
# Initialize the class with all data missing
epw_obj = cls(None)
epw_obj._is_header_loaded = True
epw_obj._is_data_loaded = True
# Check required and optional keys
required_keys = ('location', 'data_collections')
option_keys_dict = ('metadata', 'heating_dict', 'cooling_dict',
'extremes_dict', 'extreme_hot_weeks', 'extreme_cold_weeks',
'typical_weeks', 'monthly_ground_temps')
for key in required_keys:
assert key in data, 'Required key "{}" is missing!'.format(key)
assert len(data['data_collections']) == epw_obj._num_of_fields, \
'The number of data_collections must be {}. Got {}.'.format(
epw_obj._num_of_fields, len(data['data_collections']))
for key in option_keys_dict:
if key not in data:
data[key] = {}
# Set the required properties of the EPW object.
epw_obj._location = Location.from_json(data['location'])
epw_obj._data = [HourlyContinuousCollection.from_json(dc)
for dc in data['data_collections']]
if 'is_leap_year' in data:
epw_obj._is_leap_year = data['is_leap_year']
if 'is_ip' in data:
epw_obj._is_ip = data['is_ip']
# Check that the required properties all make sense.
for dc in epw_obj._data:
assert isinstance(dc, HourlyContinuousCollection), 'data_collections must ' \
'be of HourlyContinuousCollection schema. Got {}'.format(type(dc))
assert dc.header.analysis_period.is_annual, 'data_collections ' \
'analysis_period must be annual.'
assert dc.header.analysis_period.is_leap_year == epw_obj._is_leap_year, \
'data_collections is_leap_year is not aligned with that of the EPW.'
# Set all of the header properties if they exist in the dictionary.
epw_obj._metadata = data['metadata']
epw_obj.heating_design_condition_dictionary = data['heating_dict']
epw_obj.cooling_design_condition_dictionary = data['cooling_dict']
epw_obj.extreme_design_condition_dictionary = data['extremes_dict']
def _dejson(parent_dict, obj):
new_dict = {}
for key, val in parent_dict.items():
new_dict[key] = obj.from_json(val)
return new_dict
epw_obj.extreme_hot_weeks = _dejson(data['extreme_hot_weeks'], AnalysisPeriod)
epw_obj.extreme_cold_weeks = _dejson(data['extreme_cold_weeks'], AnalysisPeriod)
epw_obj.typical_weeks = _dejson(data['typical_weeks'], AnalysisPeriod)
epw_obj.monthly_ground_temperature = _dejson(
data['monthly_ground_temps'], MonthlyCollection)
if 'daylight_savings_start' in data:
epw_obj.daylight_savings_start = data['daylight_savings_start']
if 'daylight_savings_end' in data:
epw_obj.daylight_savings_end = data['daylight_savings_end']
if 'comments_1' in data:
epw_obj.comments_1 = data['comments_1']
if 'comments_2' in data:
epw_obj.comments_2 = data['comments_2']
return epw_obj | [
"def",
"from_json",
"(",
"cls",
",",
"data",
")",
":",
"# Initialize the class with all data missing",
"epw_obj",
"=",
"cls",
"(",
"None",
")",
"epw_obj",
".",
"_is_header_loaded",
"=",
"True",
"epw_obj",
".",
"_is_data_loaded",
"=",
"True",
"# Check required and optional keys",
"required_keys",
"=",
"(",
"'location'",
",",
"'data_collections'",
")",
"option_keys_dict",
"=",
"(",
"'metadata'",
",",
"'heating_dict'",
",",
"'cooling_dict'",
",",
"'extremes_dict'",
",",
"'extreme_hot_weeks'",
",",
"'extreme_cold_weeks'",
",",
"'typical_weeks'",
",",
"'monthly_ground_temps'",
")",
"for",
"key",
"in",
"required_keys",
":",
"assert",
"key",
"in",
"data",
",",
"'Required key \"{}\" is missing!'",
".",
"format",
"(",
"key",
")",
"assert",
"len",
"(",
"data",
"[",
"'data_collections'",
"]",
")",
"==",
"epw_obj",
".",
"_num_of_fields",
",",
"'The number of data_collections must be {}. Got {}.'",
".",
"format",
"(",
"epw_obj",
".",
"_num_of_fields",
",",
"len",
"(",
"data",
"[",
"'data_collections'",
"]",
")",
")",
"for",
"key",
"in",
"option_keys_dict",
":",
"if",
"key",
"not",
"in",
"data",
":",
"data",
"[",
"key",
"]",
"=",
"{",
"}",
"# Set the required properties of the EPW object.",
"epw_obj",
".",
"_location",
"=",
"Location",
".",
"from_json",
"(",
"data",
"[",
"'location'",
"]",
")",
"epw_obj",
".",
"_data",
"=",
"[",
"HourlyContinuousCollection",
".",
"from_json",
"(",
"dc",
")",
"for",
"dc",
"in",
"data",
"[",
"'data_collections'",
"]",
"]",
"if",
"'is_leap_year'",
"in",
"data",
":",
"epw_obj",
".",
"_is_leap_year",
"=",
"data",
"[",
"'is_leap_year'",
"]",
"if",
"'is_ip'",
"in",
"data",
":",
"epw_obj",
".",
"_is_ip",
"=",
"data",
"[",
"'is_ip'",
"]",
"# Check that the required properties all make sense.",
"for",
"dc",
"in",
"epw_obj",
".",
"_data",
":",
"assert",
"isinstance",
"(",
"dc",
",",
"HourlyContinuousCollection",
")",
",",
"'data_collections must '",
"'be of HourlyContinuousCollection schema. Got {}'",
".",
"format",
"(",
"type",
"(",
"dc",
")",
")",
"assert",
"dc",
".",
"header",
".",
"analysis_period",
".",
"is_annual",
",",
"'data_collections '",
"'analysis_period must be annual.'",
"assert",
"dc",
".",
"header",
".",
"analysis_period",
".",
"is_leap_year",
"==",
"epw_obj",
".",
"_is_leap_year",
",",
"'data_collections is_leap_year is not aligned with that of the EPW.'",
"# Set all of the header properties if they exist in the dictionary.",
"epw_obj",
".",
"_metadata",
"=",
"data",
"[",
"'metadata'",
"]",
"epw_obj",
".",
"heating_design_condition_dictionary",
"=",
"data",
"[",
"'heating_dict'",
"]",
"epw_obj",
".",
"cooling_design_condition_dictionary",
"=",
"data",
"[",
"'cooling_dict'",
"]",
"epw_obj",
".",
"extreme_design_condition_dictionary",
"=",
"data",
"[",
"'extremes_dict'",
"]",
"def",
"_dejson",
"(",
"parent_dict",
",",
"obj",
")",
":",
"new_dict",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"parent_dict",
".",
"items",
"(",
")",
":",
"new_dict",
"[",
"key",
"]",
"=",
"obj",
".",
"from_json",
"(",
"val",
")",
"return",
"new_dict",
"epw_obj",
".",
"extreme_hot_weeks",
"=",
"_dejson",
"(",
"data",
"[",
"'extreme_hot_weeks'",
"]",
",",
"AnalysisPeriod",
")",
"epw_obj",
".",
"extreme_cold_weeks",
"=",
"_dejson",
"(",
"data",
"[",
"'extreme_cold_weeks'",
"]",
",",
"AnalysisPeriod",
")",
"epw_obj",
".",
"typical_weeks",
"=",
"_dejson",
"(",
"data",
"[",
"'typical_weeks'",
"]",
",",
"AnalysisPeriod",
")",
"epw_obj",
".",
"monthly_ground_temperature",
"=",
"_dejson",
"(",
"data",
"[",
"'monthly_ground_temps'",
"]",
",",
"MonthlyCollection",
")",
"if",
"'daylight_savings_start'",
"in",
"data",
":",
"epw_obj",
".",
"daylight_savings_start",
"=",
"data",
"[",
"'daylight_savings_start'",
"]",
"if",
"'daylight_savings_end'",
"in",
"data",
":",
"epw_obj",
".",
"daylight_savings_end",
"=",
"data",
"[",
"'daylight_savings_end'",
"]",
"if",
"'comments_1'",
"in",
"data",
":",
"epw_obj",
".",
"comments_1",
"=",
"data",
"[",
"'comments_1'",
"]",
"if",
"'comments_2'",
"in",
"data",
":",
"epw_obj",
".",
"comments_2",
"=",
"data",
"[",
"'comments_2'",
"]",
"return",
"epw_obj"
] | Create EPW from json dictionary.
Args:
data: {
"location": {} , // ladybug location schema
"data_collections": [], // list of hourly annual hourly data collection
schemas for each of the 35 fields within the EPW file.
"metadata": {}, // dict of metadata assigned to all data collections
"heating_dict": {}, // dict containing heating design conditions
"cooling_dict": {}, // dict containing cooling design conditions
"extremes_dict": {}, // dict containing extreme design conditions
"extreme_hot_weeks": {}, // dict with values of week-long ladybug
analysis period schemas signifying extreme hot weeks.
"extreme_cold_weeks": {}, // dict with values of week-long ladybug
analysis period schemas signifying extreme cold weeks.
"typical_weeks": {}, // dict with values of week-long ladybug
analysis period schemas signifying typical weeks.
"monthly_ground_temps": {}, // dict with keys as floats signifying
depths in meters below ground and values of monthly collection schema
"is_ip": Boolean // denote whether the data is in IP units
"is_leap_year": Boolean, // denote whether data is for a leap year
"daylight_savings_start": 0, // signify when daylight savings starts
or 0 for no daylight savings
"daylight_savings_end" 0, // signify when daylight savings ends
or 0 for no daylight savings
"comments_1": String, // epw comments
"comments_2": String // epw comments
} | [
"Create",
"EPW",
"from",
"json",
"dictionary",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L181-L274 | train | 237,479 |
ladybug-tools/ladybug | ladybug/epw.py | EPW.annual_cooling_design_day_010 | def annual_cooling_design_day_010(self):
"""A design day object representing the annual 1.0% cooling design day."""
self._load_header_check()
if bool(self._cooling_dict) is True:
avg_press = self.atmospheric_station_pressure.average
avg_press = None if avg_press == 999999 else avg_press
return DesignDay.from_ashrae_dict_cooling(
self._cooling_dict, self.location, True, avg_press)
else:
return None | python | def annual_cooling_design_day_010(self):
"""A design day object representing the annual 1.0% cooling design day."""
self._load_header_check()
if bool(self._cooling_dict) is True:
avg_press = self.atmospheric_station_pressure.average
avg_press = None if avg_press == 999999 else avg_press
return DesignDay.from_ashrae_dict_cooling(
self._cooling_dict, self.location, True, avg_press)
else:
return None | [
"def",
"annual_cooling_design_day_010",
"(",
"self",
")",
":",
"self",
".",
"_load_header_check",
"(",
")",
"if",
"bool",
"(",
"self",
".",
"_cooling_dict",
")",
"is",
"True",
":",
"avg_press",
"=",
"self",
".",
"atmospheric_station_pressure",
".",
"average",
"avg_press",
"=",
"None",
"if",
"avg_press",
"==",
"999999",
"else",
"avg_press",
"return",
"DesignDay",
".",
"from_ashrae_dict_cooling",
"(",
"self",
".",
"_cooling_dict",
",",
"self",
".",
"location",
",",
"True",
",",
"avg_press",
")",
"else",
":",
"return",
"None"
] | A design day object representing the annual 1.0% cooling design day. | [
"A",
"design",
"day",
"object",
"representing",
"the",
"annual",
"1",
".",
"0%",
"cooling",
"design",
"day",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L364-L373 | train | 237,480 |
ladybug-tools/ladybug | ladybug/epw.py | EPW._des_dict_check | def _des_dict_check(self, des_dict, req_keys, cond_name):
"""Check if an input design condition dictionary is acceptable."""
assert isinstance(des_dict, dict), '{}' \
' must be a dictionary. Got {}.'.format(cond_name, type(des_dict))
if bool(des_dict) is True:
input_keys = list(des_dict.keys())
for key in req_keys:
assert key in input_keys, 'Required key "{}" was not found in ' \
'{}'.format(key, cond_name) | python | def _des_dict_check(self, des_dict, req_keys, cond_name):
"""Check if an input design condition dictionary is acceptable."""
assert isinstance(des_dict, dict), '{}' \
' must be a dictionary. Got {}.'.format(cond_name, type(des_dict))
if bool(des_dict) is True:
input_keys = list(des_dict.keys())
for key in req_keys:
assert key in input_keys, 'Required key "{}" was not found in ' \
'{}'.format(key, cond_name) | [
"def",
"_des_dict_check",
"(",
"self",
",",
"des_dict",
",",
"req_keys",
",",
"cond_name",
")",
":",
"assert",
"isinstance",
"(",
"des_dict",
",",
"dict",
")",
",",
"'{}'",
"' must be a dictionary. Got {}.'",
".",
"format",
"(",
"cond_name",
",",
"type",
"(",
"des_dict",
")",
")",
"if",
"bool",
"(",
"des_dict",
")",
"is",
"True",
":",
"input_keys",
"=",
"list",
"(",
"des_dict",
".",
"keys",
"(",
")",
")",
"for",
"key",
"in",
"req_keys",
":",
"assert",
"key",
"in",
"input_keys",
",",
"'Required key \"{}\" was not found in '",
"'{}'",
".",
"format",
"(",
"key",
",",
"cond_name",
")"
] | Check if an input design condition dictionary is acceptable. | [
"Check",
"if",
"an",
"input",
"design",
"condition",
"dictionary",
"is",
"acceptable",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L482-L490 | train | 237,481 |
ladybug-tools/ladybug | ladybug/epw.py | EPW._format_week | def _format_week(self, name, type, a_per):
"""Format an AnalysisPeriod into string for the EPW header."""
return '{},{},{}/{},{}/{}'.format(name, type, a_per.st_month, a_per.st_day,
a_per.end_month, a_per.end_day) | python | def _format_week(self, name, type, a_per):
"""Format an AnalysisPeriod into string for the EPW header."""
return '{},{},{}/{},{}/{}'.format(name, type, a_per.st_month, a_per.st_day,
a_per.end_month, a_per.end_day) | [
"def",
"_format_week",
"(",
"self",
",",
"name",
",",
"type",
",",
"a_per",
")",
":",
"return",
"'{},{},{}/{},{}/{}'",
".",
"format",
"(",
"name",
",",
"type",
",",
"a_per",
".",
"st_month",
",",
"a_per",
".",
"st_day",
",",
"a_per",
".",
"end_month",
",",
"a_per",
".",
"end_day",
")"
] | Format an AnalysisPeriod into string for the EPW header. | [
"Format",
"an",
"AnalysisPeriod",
"into",
"string",
"for",
"the",
"EPW",
"header",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L709-L712 | train | 237,482 |
ladybug-tools/ladybug | ladybug/epw.py | EPW._format_grndt | def _format_grndt(self, data_c):
"""Format monthly ground data collection into string for the EPW header."""
monthly_str = '{},{},{},{}'.format(
data_c.header.metadata['soil conductivity'],
data_c.header.metadata['soil density'],
data_c.header.metadata['soil specific heat'],
','.join(['%.2f' % x for x in data_c.values]))
return monthly_str | python | def _format_grndt(self, data_c):
"""Format monthly ground data collection into string for the EPW header."""
monthly_str = '{},{},{},{}'.format(
data_c.header.metadata['soil conductivity'],
data_c.header.metadata['soil density'],
data_c.header.metadata['soil specific heat'],
','.join(['%.2f' % x for x in data_c.values]))
return monthly_str | [
"def",
"_format_grndt",
"(",
"self",
",",
"data_c",
")",
":",
"monthly_str",
"=",
"'{},{},{},{}'",
".",
"format",
"(",
"data_c",
".",
"header",
".",
"metadata",
"[",
"'soil conductivity'",
"]",
",",
"data_c",
".",
"header",
".",
"metadata",
"[",
"'soil density'",
"]",
",",
"data_c",
".",
"header",
".",
"metadata",
"[",
"'soil specific heat'",
"]",
",",
"','",
".",
"join",
"(",
"[",
"'%.2f'",
"%",
"x",
"for",
"x",
"in",
"data_c",
".",
"values",
"]",
")",
")",
"return",
"monthly_str"
] | Format monthly ground data collection into string for the EPW header. | [
"Format",
"monthly",
"ground",
"data",
"collection",
"into",
"string",
"for",
"the",
"EPW",
"header",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L714-L721 | train | 237,483 |
ladybug-tools/ladybug | ladybug/epw.py | EPW.save | def save(self, file_path):
"""Save epw object as an epw file.
args:
file_path: A string representing the path to write the epw file to.
"""
# load data if it's not loaded convert to SI if it is in IP
if not self.is_data_loaded:
self._import_data()
originally_ip = False
if self.is_ip is True:
self.convert_to_si()
originally_ip = True
# write the file
lines = self.header
try:
# if the first value is at 1AM, move first item to end position
for field in xrange(0, self._num_of_fields):
point_in_time = self._data[field].header.data_type.point_in_time
if point_in_time is True:
first_hour = self._data[field]._values.pop(0)
self._data[field]._values.append(first_hour)
annual_a_per = AnalysisPeriod(is_leap_year=self.is_leap_year)
for hour in xrange(0, len(annual_a_per.datetimes)):
line = []
for field in xrange(0, self._num_of_fields):
line.append(str(self._data[field]._values[hour]))
lines.append(",".join(line) + "\n")
except IndexError:
# cleaning up
length_error_msg = 'Data length is not for a full year and cannot be ' + \
'saved as an EPW file.'
raise ValueError(length_error_msg)
else:
file_data = ''.join(lines)
write_to_file(file_path, file_data, True)
finally:
del(lines)
# move last item to start position for fields on the hour
for field in xrange(0, self._num_of_fields):
point_in_time = self._data[field].header.data_type.point_in_time
if point_in_time is True:
last_hour = self._data[field]._values.pop()
self._data[field]._values.insert(0, last_hour)
if originally_ip is True:
self.convert_to_ip()
return file_path | python | def save(self, file_path):
"""Save epw object as an epw file.
args:
file_path: A string representing the path to write the epw file to.
"""
# load data if it's not loaded convert to SI if it is in IP
if not self.is_data_loaded:
self._import_data()
originally_ip = False
if self.is_ip is True:
self.convert_to_si()
originally_ip = True
# write the file
lines = self.header
try:
# if the first value is at 1AM, move first item to end position
for field in xrange(0, self._num_of_fields):
point_in_time = self._data[field].header.data_type.point_in_time
if point_in_time is True:
first_hour = self._data[field]._values.pop(0)
self._data[field]._values.append(first_hour)
annual_a_per = AnalysisPeriod(is_leap_year=self.is_leap_year)
for hour in xrange(0, len(annual_a_per.datetimes)):
line = []
for field in xrange(0, self._num_of_fields):
line.append(str(self._data[field]._values[hour]))
lines.append(",".join(line) + "\n")
except IndexError:
# cleaning up
length_error_msg = 'Data length is not for a full year and cannot be ' + \
'saved as an EPW file.'
raise ValueError(length_error_msg)
else:
file_data = ''.join(lines)
write_to_file(file_path, file_data, True)
finally:
del(lines)
# move last item to start position for fields on the hour
for field in xrange(0, self._num_of_fields):
point_in_time = self._data[field].header.data_type.point_in_time
if point_in_time is True:
last_hour = self._data[field]._values.pop()
self._data[field]._values.insert(0, last_hour)
if originally_ip is True:
self.convert_to_ip()
return file_path | [
"def",
"save",
"(",
"self",
",",
"file_path",
")",
":",
"# load data if it's not loaded convert to SI if it is in IP",
"if",
"not",
"self",
".",
"is_data_loaded",
":",
"self",
".",
"_import_data",
"(",
")",
"originally_ip",
"=",
"False",
"if",
"self",
".",
"is_ip",
"is",
"True",
":",
"self",
".",
"convert_to_si",
"(",
")",
"originally_ip",
"=",
"True",
"# write the file",
"lines",
"=",
"self",
".",
"header",
"try",
":",
"# if the first value is at 1AM, move first item to end position",
"for",
"field",
"in",
"xrange",
"(",
"0",
",",
"self",
".",
"_num_of_fields",
")",
":",
"point_in_time",
"=",
"self",
".",
"_data",
"[",
"field",
"]",
".",
"header",
".",
"data_type",
".",
"point_in_time",
"if",
"point_in_time",
"is",
"True",
":",
"first_hour",
"=",
"self",
".",
"_data",
"[",
"field",
"]",
".",
"_values",
".",
"pop",
"(",
"0",
")",
"self",
".",
"_data",
"[",
"field",
"]",
".",
"_values",
".",
"append",
"(",
"first_hour",
")",
"annual_a_per",
"=",
"AnalysisPeriod",
"(",
"is_leap_year",
"=",
"self",
".",
"is_leap_year",
")",
"for",
"hour",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"annual_a_per",
".",
"datetimes",
")",
")",
":",
"line",
"=",
"[",
"]",
"for",
"field",
"in",
"xrange",
"(",
"0",
",",
"self",
".",
"_num_of_fields",
")",
":",
"line",
".",
"append",
"(",
"str",
"(",
"self",
".",
"_data",
"[",
"field",
"]",
".",
"_values",
"[",
"hour",
"]",
")",
")",
"lines",
".",
"append",
"(",
"\",\"",
".",
"join",
"(",
"line",
")",
"+",
"\"\\n\"",
")",
"except",
"IndexError",
":",
"# cleaning up",
"length_error_msg",
"=",
"'Data length is not for a full year and cannot be '",
"+",
"'saved as an EPW file.'",
"raise",
"ValueError",
"(",
"length_error_msg",
")",
"else",
":",
"file_data",
"=",
"''",
".",
"join",
"(",
"lines",
")",
"write_to_file",
"(",
"file_path",
",",
"file_data",
",",
"True",
")",
"finally",
":",
"del",
"(",
"lines",
")",
"# move last item to start position for fields on the hour",
"for",
"field",
"in",
"xrange",
"(",
"0",
",",
"self",
".",
"_num_of_fields",
")",
":",
"point_in_time",
"=",
"self",
".",
"_data",
"[",
"field",
"]",
".",
"header",
".",
"data_type",
".",
"point_in_time",
"if",
"point_in_time",
"is",
"True",
":",
"last_hour",
"=",
"self",
".",
"_data",
"[",
"field",
"]",
".",
"_values",
".",
"pop",
"(",
")",
"self",
".",
"_data",
"[",
"field",
"]",
".",
"_values",
".",
"insert",
"(",
"0",
",",
"last_hour",
")",
"if",
"originally_ip",
"is",
"True",
":",
"self",
".",
"convert_to_ip",
"(",
")",
"return",
"file_path"
] | Save epw object as an epw file.
args:
file_path: A string representing the path to write the epw file to. | [
"Save",
"epw",
"object",
"as",
"an",
"epw",
"file",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L723-L773 | train | 237,484 |
ladybug-tools/ladybug | ladybug/epw.py | EPW.convert_to_ip | def convert_to_ip(self):
"""Convert all Data Collections of this EPW object to IP units.
This is useful when one knows that all graphics produced from this
EPW should be in Imperial units."""
if not self.is_data_loaded:
self._import_data()
if self.is_ip is False:
for coll in self._data:
coll.convert_to_ip()
self._is_ip = True | python | def convert_to_ip(self):
"""Convert all Data Collections of this EPW object to IP units.
This is useful when one knows that all graphics produced from this
EPW should be in Imperial units."""
if not self.is_data_loaded:
self._import_data()
if self.is_ip is False:
for coll in self._data:
coll.convert_to_ip()
self._is_ip = True | [
"def",
"convert_to_ip",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_data_loaded",
":",
"self",
".",
"_import_data",
"(",
")",
"if",
"self",
".",
"is_ip",
"is",
"False",
":",
"for",
"coll",
"in",
"self",
".",
"_data",
":",
"coll",
".",
"convert_to_ip",
"(",
")",
"self",
".",
"_is_ip",
"=",
"True"
] | Convert all Data Collections of this EPW object to IP units.
This is useful when one knows that all graphics produced from this
EPW should be in Imperial units. | [
"Convert",
"all",
"Data",
"Collections",
"of",
"this",
"EPW",
"object",
"to",
"IP",
"units",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L775-L785 | train | 237,485 |
ladybug-tools/ladybug | ladybug/epw.py | EPW._get_data_by_field | def _get_data_by_field(self, field_number):
"""Return a data field by field number.
This is a useful method to get the values for fields that Ladybug
currently doesn't import by default. You can find list of fields by typing
EPWFields.fields
Args:
field_number: a value between 0 to 34 for different available epw fields.
Returns:
An annual Ladybug list
"""
if not self.is_data_loaded:
self._import_data()
# check input data
if not 0 <= field_number < self._num_of_fields:
raise ValueError("Field number should be between 0-%d" % self._num_of_fields)
return self._data[field_number] | python | def _get_data_by_field(self, field_number):
"""Return a data field by field number.
This is a useful method to get the values for fields that Ladybug
currently doesn't import by default. You can find list of fields by typing
EPWFields.fields
Args:
field_number: a value between 0 to 34 for different available epw fields.
Returns:
An annual Ladybug list
"""
if not self.is_data_loaded:
self._import_data()
# check input data
if not 0 <= field_number < self._num_of_fields:
raise ValueError("Field number should be between 0-%d" % self._num_of_fields)
return self._data[field_number] | [
"def",
"_get_data_by_field",
"(",
"self",
",",
"field_number",
")",
":",
"if",
"not",
"self",
".",
"is_data_loaded",
":",
"self",
".",
"_import_data",
"(",
")",
"# check input data",
"if",
"not",
"0",
"<=",
"field_number",
"<",
"self",
".",
"_num_of_fields",
":",
"raise",
"ValueError",
"(",
"\"Field number should be between 0-%d\"",
"%",
"self",
".",
"_num_of_fields",
")",
"return",
"self",
".",
"_data",
"[",
"field_number",
"]"
] | Return a data field by field number.
This is a useful method to get the values for fields that Ladybug
currently doesn't import by default. You can find list of fields by typing
EPWFields.fields
Args:
field_number: a value between 0 to 34 for different available epw fields.
Returns:
An annual Ladybug list | [
"Return",
"a",
"data",
"field",
"by",
"field",
"number",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L800-L820 | train | 237,486 |
ladybug-tools/ladybug | ladybug/epw.py | EPW.sky_temperature | def sky_temperature(self):
"""Return annual Sky Temperature as a Ladybug Data Collection.
This value in degrees Celcius is derived from the Horizontal Infrared
Radiation Intensity in Wh/m2. It represents the long wave radiant
temperature of the sky
Read more at: https://bigladdersoftware.com/epx/docs/8-9/engineering-reference
/climate-calculations.html#energyplus-sky-temperature-calculation
"""
# create sky temperature header
sky_temp_header = Header(data_type=temperature.SkyTemperature(), unit='C',
analysis_period=AnalysisPeriod(),
metadata=self._metadata)
# calculate sy temperature for each hour
horiz_ir = self._get_data_by_field(12).values
sky_temp_data = [calc_sky_temperature(hir) for hir in horiz_ir]
return HourlyContinuousCollection(sky_temp_header, sky_temp_data) | python | def sky_temperature(self):
"""Return annual Sky Temperature as a Ladybug Data Collection.
This value in degrees Celcius is derived from the Horizontal Infrared
Radiation Intensity in Wh/m2. It represents the long wave radiant
temperature of the sky
Read more at: https://bigladdersoftware.com/epx/docs/8-9/engineering-reference
/climate-calculations.html#energyplus-sky-temperature-calculation
"""
# create sky temperature header
sky_temp_header = Header(data_type=temperature.SkyTemperature(), unit='C',
analysis_period=AnalysisPeriod(),
metadata=self._metadata)
# calculate sy temperature for each hour
horiz_ir = self._get_data_by_field(12).values
sky_temp_data = [calc_sky_temperature(hir) for hir in horiz_ir]
return HourlyContinuousCollection(sky_temp_header, sky_temp_data) | [
"def",
"sky_temperature",
"(",
"self",
")",
":",
"# create sky temperature header",
"sky_temp_header",
"=",
"Header",
"(",
"data_type",
"=",
"temperature",
".",
"SkyTemperature",
"(",
")",
",",
"unit",
"=",
"'C'",
",",
"analysis_period",
"=",
"AnalysisPeriod",
"(",
")",
",",
"metadata",
"=",
"self",
".",
"_metadata",
")",
"# calculate sy temperature for each hour",
"horiz_ir",
"=",
"self",
".",
"_get_data_by_field",
"(",
"12",
")",
".",
"values",
"sky_temp_data",
"=",
"[",
"calc_sky_temperature",
"(",
"hir",
")",
"for",
"hir",
"in",
"horiz_ir",
"]",
"return",
"HourlyContinuousCollection",
"(",
"sky_temp_header",
",",
"sky_temp_data",
")"
] | Return annual Sky Temperature as a Ladybug Data Collection.
This value in degrees Celcius is derived from the Horizontal Infrared
Radiation Intensity in Wh/m2. It represents the long wave radiant
temperature of the sky
Read more at: https://bigladdersoftware.com/epx/docs/8-9/engineering-reference
/climate-calculations.html#energyplus-sky-temperature-calculation | [
"Return",
"annual",
"Sky",
"Temperature",
"as",
"a",
"Ladybug",
"Data",
"Collection",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L1275-L1292 | train | 237,487 |
ladybug-tools/ladybug | ladybug/epw.py | EPW.to_wea | def to_wea(self, file_path, hoys=None):
"""Write an wea file from the epw file.
WEA carries radiation values from epw. Gendaymtx uses these values to
generate the sky. For an annual analysis it is identical to using epw2wea.
args:
file_path: Full file path for output file.
hoys: List of hours of the year. Default is 0-8759.
"""
hoys = hoys or xrange(len(self.direct_normal_radiation.datetimes))
if not file_path.lower().endswith('.wea'):
file_path += '.wea'
originally_ip = False
if self.is_ip is True:
self.convert_to_si()
originally_ip = True
# write header
lines = [self._get_wea_header()]
# write values
datetimes = self.direct_normal_radiation.datetimes
for hoy in hoys:
dir_rad = self.direct_normal_radiation[hoy]
dif_rad = self.diffuse_horizontal_radiation[hoy]
line = "%d %d %.3f %d %d\n" \
% (datetimes[hoy].month,
datetimes[hoy].day,
datetimes[hoy].hour + 0.5,
dir_rad, dif_rad)
lines.append(line)
file_data = ''.join(lines)
write_to_file(file_path, file_data, True)
if originally_ip is True:
self.convert_to_ip()
return file_path | python | def to_wea(self, file_path, hoys=None):
"""Write an wea file from the epw file.
WEA carries radiation values from epw. Gendaymtx uses these values to
generate the sky. For an annual analysis it is identical to using epw2wea.
args:
file_path: Full file path for output file.
hoys: List of hours of the year. Default is 0-8759.
"""
hoys = hoys or xrange(len(self.direct_normal_radiation.datetimes))
if not file_path.lower().endswith('.wea'):
file_path += '.wea'
originally_ip = False
if self.is_ip is True:
self.convert_to_si()
originally_ip = True
# write header
lines = [self._get_wea_header()]
# write values
datetimes = self.direct_normal_radiation.datetimes
for hoy in hoys:
dir_rad = self.direct_normal_radiation[hoy]
dif_rad = self.diffuse_horizontal_radiation[hoy]
line = "%d %d %.3f %d %d\n" \
% (datetimes[hoy].month,
datetimes[hoy].day,
datetimes[hoy].hour + 0.5,
dir_rad, dif_rad)
lines.append(line)
file_data = ''.join(lines)
write_to_file(file_path, file_data, True)
if originally_ip is True:
self.convert_to_ip()
return file_path | [
"def",
"to_wea",
"(",
"self",
",",
"file_path",
",",
"hoys",
"=",
"None",
")",
":",
"hoys",
"=",
"hoys",
"or",
"xrange",
"(",
"len",
"(",
"self",
".",
"direct_normal_radiation",
".",
"datetimes",
")",
")",
"if",
"not",
"file_path",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.wea'",
")",
":",
"file_path",
"+=",
"'.wea'",
"originally_ip",
"=",
"False",
"if",
"self",
".",
"is_ip",
"is",
"True",
":",
"self",
".",
"convert_to_si",
"(",
")",
"originally_ip",
"=",
"True",
"# write header",
"lines",
"=",
"[",
"self",
".",
"_get_wea_header",
"(",
")",
"]",
"# write values",
"datetimes",
"=",
"self",
".",
"direct_normal_radiation",
".",
"datetimes",
"for",
"hoy",
"in",
"hoys",
":",
"dir_rad",
"=",
"self",
".",
"direct_normal_radiation",
"[",
"hoy",
"]",
"dif_rad",
"=",
"self",
".",
"diffuse_horizontal_radiation",
"[",
"hoy",
"]",
"line",
"=",
"\"%d %d %.3f %d %d\\n\"",
"%",
"(",
"datetimes",
"[",
"hoy",
"]",
".",
"month",
",",
"datetimes",
"[",
"hoy",
"]",
".",
"day",
",",
"datetimes",
"[",
"hoy",
"]",
".",
"hour",
"+",
"0.5",
",",
"dir_rad",
",",
"dif_rad",
")",
"lines",
".",
"append",
"(",
"line",
")",
"file_data",
"=",
"''",
".",
"join",
"(",
"lines",
")",
"write_to_file",
"(",
"file_path",
",",
"file_data",
",",
"True",
")",
"if",
"originally_ip",
"is",
"True",
":",
"self",
".",
"convert_to_ip",
"(",
")",
"return",
"file_path"
] | Write an wea file from the epw file.
WEA carries radiation values from epw. Gendaymtx uses these values to
generate the sky. For an annual analysis it is identical to using epw2wea.
args:
file_path: Full file path for output file.
hoys: List of hours of the year. Default is 0-8759. | [
"Write",
"an",
"wea",
"file",
"from",
"the",
"epw",
"file",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L1302-L1341 | train | 237,488 |
ladybug-tools/ladybug | ladybug/epw.py | EPW.to_json | def to_json(self):
"""Convert the EPW to a dictionary."""
# load data if it's not loaded
if not self.is_data_loaded:
self._import_data()
def jsonify_dict(base_dict):
new_dict = {}
for key, val in base_dict.items():
new_dict[key] = val.to_json()
return new_dict
hot_wks = jsonify_dict(self.extreme_hot_weeks)
cold_wks = jsonify_dict(self.extreme_cold_weeks)
typ_wks = jsonify_dict(self.typical_weeks)
grnd_temps = jsonify_dict(self.monthly_ground_temperature)
return {
'location': self.location.to_json(),
'data_collections': [dc.to_json() for dc in self._data],
'metadata': self.metadata,
'heating_dict': self.heating_design_condition_dictionary,
'cooling_dict': self.cooling_design_condition_dictionary,
'extremes_dict': self.extreme_design_condition_dictionary,
'extreme_hot_weeks': hot_wks,
'extreme_cold_weeks': cold_wks,
'typical_weeks': typ_wks,
"monthly_ground_temps": grnd_temps,
"is_ip": self._is_ip,
"is_leap_year": self.is_leap_year,
"daylight_savings_start": self.daylight_savings_start,
"daylight_savings_end": self.daylight_savings_end,
"comments_1": self.comments_1,
"comments_2": self.comments_2
} | python | def to_json(self):
"""Convert the EPW to a dictionary."""
# load data if it's not loaded
if not self.is_data_loaded:
self._import_data()
def jsonify_dict(base_dict):
new_dict = {}
for key, val in base_dict.items():
new_dict[key] = val.to_json()
return new_dict
hot_wks = jsonify_dict(self.extreme_hot_weeks)
cold_wks = jsonify_dict(self.extreme_cold_weeks)
typ_wks = jsonify_dict(self.typical_weeks)
grnd_temps = jsonify_dict(self.monthly_ground_temperature)
return {
'location': self.location.to_json(),
'data_collections': [dc.to_json() for dc in self._data],
'metadata': self.metadata,
'heating_dict': self.heating_design_condition_dictionary,
'cooling_dict': self.cooling_design_condition_dictionary,
'extremes_dict': self.extreme_design_condition_dictionary,
'extreme_hot_weeks': hot_wks,
'extreme_cold_weeks': cold_wks,
'typical_weeks': typ_wks,
"monthly_ground_temps": grnd_temps,
"is_ip": self._is_ip,
"is_leap_year": self.is_leap_year,
"daylight_savings_start": self.daylight_savings_start,
"daylight_savings_end": self.daylight_savings_end,
"comments_1": self.comments_1,
"comments_2": self.comments_2
} | [
"def",
"to_json",
"(",
"self",
")",
":",
"# load data if it's not loaded",
"if",
"not",
"self",
".",
"is_data_loaded",
":",
"self",
".",
"_import_data",
"(",
")",
"def",
"jsonify_dict",
"(",
"base_dict",
")",
":",
"new_dict",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"base_dict",
".",
"items",
"(",
")",
":",
"new_dict",
"[",
"key",
"]",
"=",
"val",
".",
"to_json",
"(",
")",
"return",
"new_dict",
"hot_wks",
"=",
"jsonify_dict",
"(",
"self",
".",
"extreme_hot_weeks",
")",
"cold_wks",
"=",
"jsonify_dict",
"(",
"self",
".",
"extreme_cold_weeks",
")",
"typ_wks",
"=",
"jsonify_dict",
"(",
"self",
".",
"typical_weeks",
")",
"grnd_temps",
"=",
"jsonify_dict",
"(",
"self",
".",
"monthly_ground_temperature",
")",
"return",
"{",
"'location'",
":",
"self",
".",
"location",
".",
"to_json",
"(",
")",
",",
"'data_collections'",
":",
"[",
"dc",
".",
"to_json",
"(",
")",
"for",
"dc",
"in",
"self",
".",
"_data",
"]",
",",
"'metadata'",
":",
"self",
".",
"metadata",
",",
"'heating_dict'",
":",
"self",
".",
"heating_design_condition_dictionary",
",",
"'cooling_dict'",
":",
"self",
".",
"cooling_design_condition_dictionary",
",",
"'extremes_dict'",
":",
"self",
".",
"extreme_design_condition_dictionary",
",",
"'extreme_hot_weeks'",
":",
"hot_wks",
",",
"'extreme_cold_weeks'",
":",
"cold_wks",
",",
"'typical_weeks'",
":",
"typ_wks",
",",
"\"monthly_ground_temps\"",
":",
"grnd_temps",
",",
"\"is_ip\"",
":",
"self",
".",
"_is_ip",
",",
"\"is_leap_year\"",
":",
"self",
".",
"is_leap_year",
",",
"\"daylight_savings_start\"",
":",
"self",
".",
"daylight_savings_start",
",",
"\"daylight_savings_end\"",
":",
"self",
".",
"daylight_savings_end",
",",
"\"comments_1\"",
":",
"self",
".",
"comments_1",
",",
"\"comments_2\"",
":",
"self",
".",
"comments_2",
"}"
] | Convert the EPW to a dictionary. | [
"Convert",
"the",
"EPW",
"to",
"a",
"dictionary",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/epw.py#L1343-L1375 | train | 237,489 |
ladybug-tools/ladybug | ladybug/analysisperiod.py | AnalysisPeriod.from_analysis_period | def from_analysis_period(cls, analysis_period=None):
"""Create and AnalysisPeriod from an analysis period.
This method is useful to be called from inside Grasshopper or Dynamo
"""
if not analysis_period:
return cls()
elif hasattr(analysis_period, 'isAnalysisPeriod'):
return analysis_period
elif isinstance(analysis_period, str):
try:
return cls.from_string(analysis_period)
except Exception as e:
raise ValueError(
"{} is not convertable to an AnalysisPeriod: {}".format(
analysis_period, e)
) | python | def from_analysis_period(cls, analysis_period=None):
"""Create and AnalysisPeriod from an analysis period.
This method is useful to be called from inside Grasshopper or Dynamo
"""
if not analysis_period:
return cls()
elif hasattr(analysis_period, 'isAnalysisPeriod'):
return analysis_period
elif isinstance(analysis_period, str):
try:
return cls.from_string(analysis_period)
except Exception as e:
raise ValueError(
"{} is not convertable to an AnalysisPeriod: {}".format(
analysis_period, e)
) | [
"def",
"from_analysis_period",
"(",
"cls",
",",
"analysis_period",
"=",
"None",
")",
":",
"if",
"not",
"analysis_period",
":",
"return",
"cls",
"(",
")",
"elif",
"hasattr",
"(",
"analysis_period",
",",
"'isAnalysisPeriod'",
")",
":",
"return",
"analysis_period",
"elif",
"isinstance",
"(",
"analysis_period",
",",
"str",
")",
":",
"try",
":",
"return",
"cls",
".",
"from_string",
"(",
"analysis_period",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"ValueError",
"(",
"\"{} is not convertable to an AnalysisPeriod: {}\"",
".",
"format",
"(",
"analysis_period",
",",
"e",
")",
")"
] | Create and AnalysisPeriod from an analysis period.
This method is useful to be called from inside Grasshopper or Dynamo | [
"Create",
"and",
"AnalysisPeriod",
"from",
"an",
"analysis",
"period",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L161-L177 | train | 237,490 |
ladybug-tools/ladybug | ladybug/analysisperiod.py | AnalysisPeriod.from_string | def from_string(cls, analysis_period_string):
"""Create an Analysis Period object from an analysis period string.
%s/%s to %s/%s between %s and %s @%s
"""
# %s/%s to %s/%s between %s to %s @%s*
is_leap_year = True if analysis_period_string.strip()[-1] == '*' else False
ap = analysis_period_string.lower().replace(' ', '') \
.replace('to', ' ') \
.replace('and', ' ') \
.replace('/', ' ') \
.replace('between', ' ') \
.replace('@', ' ') \
.replace('*', '')
try:
st_month, st_day, end_month, end_day, \
st_hour, end_hour, timestep = ap.split(' ')
return cls(st_month, st_day, st_hour, end_month,
end_day, end_hour, int(timestep), is_leap_year)
except Exception as e:
raise ValueError(str(e)) | python | def from_string(cls, analysis_period_string):
"""Create an Analysis Period object from an analysis period string.
%s/%s to %s/%s between %s and %s @%s
"""
# %s/%s to %s/%s between %s to %s @%s*
is_leap_year = True if analysis_period_string.strip()[-1] == '*' else False
ap = analysis_period_string.lower().replace(' ', '') \
.replace('to', ' ') \
.replace('and', ' ') \
.replace('/', ' ') \
.replace('between', ' ') \
.replace('@', ' ') \
.replace('*', '')
try:
st_month, st_day, end_month, end_day, \
st_hour, end_hour, timestep = ap.split(' ')
return cls(st_month, st_day, st_hour, end_month,
end_day, end_hour, int(timestep), is_leap_year)
except Exception as e:
raise ValueError(str(e)) | [
"def",
"from_string",
"(",
"cls",
",",
"analysis_period_string",
")",
":",
"# %s/%s to %s/%s between %s to %s @%s*",
"is_leap_year",
"=",
"True",
"if",
"analysis_period_string",
".",
"strip",
"(",
")",
"[",
"-",
"1",
"]",
"==",
"'*'",
"else",
"False",
"ap",
"=",
"analysis_period_string",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"' '",
",",
"''",
")",
".",
"replace",
"(",
"'to'",
",",
"' '",
")",
".",
"replace",
"(",
"'and'",
",",
"' '",
")",
".",
"replace",
"(",
"'/'",
",",
"' '",
")",
".",
"replace",
"(",
"'between'",
",",
"' '",
")",
".",
"replace",
"(",
"'@'",
",",
"' '",
")",
".",
"replace",
"(",
"'*'",
",",
"''",
")",
"try",
":",
"st_month",
",",
"st_day",
",",
"end_month",
",",
"end_day",
",",
"st_hour",
",",
"end_hour",
",",
"timestep",
"=",
"ap",
".",
"split",
"(",
"' '",
")",
"return",
"cls",
"(",
"st_month",
",",
"st_day",
",",
"st_hour",
",",
"end_month",
",",
"end_day",
",",
"end_hour",
",",
"int",
"(",
"timestep",
")",
",",
"is_leap_year",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"ValueError",
"(",
"str",
"(",
"e",
")",
")"
] | Create an Analysis Period object from an analysis period string.
%s/%s to %s/%s between %s and %s @%s | [
"Create",
"an",
"Analysis",
"Period",
"object",
"from",
"an",
"analysis",
"period",
"string",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L180-L200 | train | 237,491 |
ladybug-tools/ladybug | ladybug/analysisperiod.py | AnalysisPeriod.datetimes | def datetimes(self):
"""A sorted list of datetimes in this analysis period."""
if self._timestamps_data is None:
self._calculate_timestamps()
return tuple(DateTime.from_moy(moy, self.is_leap_year)
for moy in self._timestamps_data) | python | def datetimes(self):
"""A sorted list of datetimes in this analysis period."""
if self._timestamps_data is None:
self._calculate_timestamps()
return tuple(DateTime.from_moy(moy, self.is_leap_year)
for moy in self._timestamps_data) | [
"def",
"datetimes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_timestamps_data",
"is",
"None",
":",
"self",
".",
"_calculate_timestamps",
"(",
")",
"return",
"tuple",
"(",
"DateTime",
".",
"from_moy",
"(",
"moy",
",",
"self",
".",
"is_leap_year",
")",
"for",
"moy",
"in",
"self",
".",
"_timestamps_data",
")"
] | A sorted list of datetimes in this analysis period. | [
"A",
"sorted",
"list",
"of",
"datetimes",
"in",
"this",
"analysis",
"period",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L258-L263 | train | 237,492 |
ladybug-tools/ladybug | ladybug/analysisperiod.py | AnalysisPeriod.hoys | def hoys(self):
"""A sorted list of hours of year in this analysis period."""
if self._timestamps_data is None:
self._calculate_timestamps()
return tuple(moy / 60.0 for moy in self._timestamps_data) | python | def hoys(self):
"""A sorted list of hours of year in this analysis period."""
if self._timestamps_data is None:
self._calculate_timestamps()
return tuple(moy / 60.0 for moy in self._timestamps_data) | [
"def",
"hoys",
"(",
"self",
")",
":",
"if",
"self",
".",
"_timestamps_data",
"is",
"None",
":",
"self",
".",
"_calculate_timestamps",
"(",
")",
"return",
"tuple",
"(",
"moy",
"/",
"60.0",
"for",
"moy",
"in",
"self",
".",
"_timestamps_data",
")"
] | A sorted list of hours of year in this analysis period. | [
"A",
"sorted",
"list",
"of",
"hours",
"of",
"year",
"in",
"this",
"analysis",
"period",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L273-L277 | train | 237,493 |
ladybug-tools/ladybug | ladybug/analysisperiod.py | AnalysisPeriod.hoys_int | def hoys_int(self):
"""A sorted list of hours of year in this analysis period as integers."""
if self._timestamps_data is None:
self._calculate_timestamps()
return tuple(int(moy / 60.0) for moy in self._timestamps_data) | python | def hoys_int(self):
"""A sorted list of hours of year in this analysis period as integers."""
if self._timestamps_data is None:
self._calculate_timestamps()
return tuple(int(moy / 60.0) for moy in self._timestamps_data) | [
"def",
"hoys_int",
"(",
"self",
")",
":",
"if",
"self",
".",
"_timestamps_data",
"is",
"None",
":",
"self",
".",
"_calculate_timestamps",
"(",
")",
"return",
"tuple",
"(",
"int",
"(",
"moy",
"/",
"60.0",
")",
"for",
"moy",
"in",
"self",
".",
"_timestamps_data",
")"
] | A sorted list of hours of year in this analysis period as integers. | [
"A",
"sorted",
"list",
"of",
"hours",
"of",
"year",
"in",
"this",
"analysis",
"period",
"as",
"integers",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L280-L284 | train | 237,494 |
ladybug-tools/ladybug | ladybug/analysisperiod.py | AnalysisPeriod.doys_int | def doys_int(self):
"""A sorted list of days of the year in this analysis period as integers."""
if not self._is_reversed:
return self._calc_daystamps(self.st_time, self.end_time)
else:
doys_st = self._calc_daystamps(self.st_time, DateTime.from_hoy(8759))
doys_end = self._calc_daystamps(DateTime.from_hoy(0), self.end_time)
return doys_st + doys_end | python | def doys_int(self):
"""A sorted list of days of the year in this analysis period as integers."""
if not self._is_reversed:
return self._calc_daystamps(self.st_time, self.end_time)
else:
doys_st = self._calc_daystamps(self.st_time, DateTime.from_hoy(8759))
doys_end = self._calc_daystamps(DateTime.from_hoy(0), self.end_time)
return doys_st + doys_end | [
"def",
"doys_int",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_is_reversed",
":",
"return",
"self",
".",
"_calc_daystamps",
"(",
"self",
".",
"st_time",
",",
"self",
".",
"end_time",
")",
"else",
":",
"doys_st",
"=",
"self",
".",
"_calc_daystamps",
"(",
"self",
".",
"st_time",
",",
"DateTime",
".",
"from_hoy",
"(",
"8759",
")",
")",
"doys_end",
"=",
"self",
".",
"_calc_daystamps",
"(",
"DateTime",
".",
"from_hoy",
"(",
"0",
")",
",",
"self",
".",
"end_time",
")",
"return",
"doys_st",
"+",
"doys_end"
] | A sorted list of days of the year in this analysis period as integers. | [
"A",
"sorted",
"list",
"of",
"days",
"of",
"the",
"year",
"in",
"this",
"analysis",
"period",
"as",
"integers",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L287-L294 | train | 237,495 |
ladybug-tools/ladybug | ladybug/analysisperiod.py | AnalysisPeriod.months_int | def months_int(self):
"""A sorted list of months of the year in this analysis period as integers."""
if not self._is_reversed:
return list(xrange(self.st_time.month, self.end_time.month + 1))
else:
months_st = list(xrange(self.st_time.month, 13))
months_end = list(xrange(1, self.end_time.month + 1))
return months_st + months_end | python | def months_int(self):
"""A sorted list of months of the year in this analysis period as integers."""
if not self._is_reversed:
return list(xrange(self.st_time.month, self.end_time.month + 1))
else:
months_st = list(xrange(self.st_time.month, 13))
months_end = list(xrange(1, self.end_time.month + 1))
return months_st + months_end | [
"def",
"months_int",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_is_reversed",
":",
"return",
"list",
"(",
"xrange",
"(",
"self",
".",
"st_time",
".",
"month",
",",
"self",
".",
"end_time",
".",
"month",
"+",
"1",
")",
")",
"else",
":",
"months_st",
"=",
"list",
"(",
"xrange",
"(",
"self",
".",
"st_time",
".",
"month",
",",
"13",
")",
")",
"months_end",
"=",
"list",
"(",
"xrange",
"(",
"1",
",",
"self",
".",
"end_time",
".",
"month",
"+",
"1",
")",
")",
"return",
"months_st",
"+",
"months_end"
] | A sorted list of months of the year in this analysis period as integers. | [
"A",
"sorted",
"list",
"of",
"months",
"of",
"the",
"year",
"in",
"this",
"analysis",
"period",
"as",
"integers",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L297-L304 | train | 237,496 |
ladybug-tools/ladybug | ladybug/analysisperiod.py | AnalysisPeriod.months_per_hour | def months_per_hour(self):
"""A list of tuples representing months per hour in this analysis period."""
month_hour = []
hour_range = xrange(self.st_hour, self.end_hour + 1)
for month in self.months_int:
month_hour.extend([(month, hr) for hr in hour_range])
return month_hour | python | def months_per_hour(self):
"""A list of tuples representing months per hour in this analysis period."""
month_hour = []
hour_range = xrange(self.st_hour, self.end_hour + 1)
for month in self.months_int:
month_hour.extend([(month, hr) for hr in hour_range])
return month_hour | [
"def",
"months_per_hour",
"(",
"self",
")",
":",
"month_hour",
"=",
"[",
"]",
"hour_range",
"=",
"xrange",
"(",
"self",
".",
"st_hour",
",",
"self",
".",
"end_hour",
"+",
"1",
")",
"for",
"month",
"in",
"self",
".",
"months_int",
":",
"month_hour",
".",
"extend",
"(",
"[",
"(",
"month",
",",
"hr",
")",
"for",
"hr",
"in",
"hour_range",
"]",
")",
"return",
"month_hour"
] | A list of tuples representing months per hour in this analysis period. | [
"A",
"list",
"of",
"tuples",
"representing",
"months",
"per",
"hour",
"in",
"this",
"analysis",
"period",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L307-L313 | train | 237,497 |
ladybug-tools/ladybug | ladybug/analysisperiod.py | AnalysisPeriod.is_annual | def is_annual(self):
"""Check if an analysis period is annual."""
if (self.st_month, self.st_day, self.st_hour, self.end_month,
self.end_day, self.end_hour) == (1, 1, 0, 12, 31, 23):
return True
else:
return False | python | def is_annual(self):
"""Check if an analysis period is annual."""
if (self.st_month, self.st_day, self.st_hour, self.end_month,
self.end_day, self.end_hour) == (1, 1, 0, 12, 31, 23):
return True
else:
return False | [
"def",
"is_annual",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"st_month",
",",
"self",
".",
"st_day",
",",
"self",
".",
"st_hour",
",",
"self",
".",
"end_month",
",",
"self",
".",
"end_day",
",",
"self",
".",
"end_hour",
")",
"==",
"(",
"1",
",",
"1",
",",
"0",
",",
"12",
",",
"31",
",",
"23",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | Check if an analysis period is annual. | [
"Check",
"if",
"an",
"analysis",
"period",
"is",
"annual",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L321-L327 | train | 237,498 |
ladybug-tools/ladybug | ladybug/analysisperiod.py | AnalysisPeriod.is_possible_hour | def is_possible_hour(self, hour):
"""Check if a float hour is a possible hour for this analysis period."""
if hour > 23 and self.is_possible_hour(0):
hour = int(hour)
if not self._is_overnight:
return self.st_time.hour <= hour <= self.end_time.hour
else:
return self.st_time.hour <= hour <= 23 or \
0 <= hour <= self.end_time.hour | python | def is_possible_hour(self, hour):
"""Check if a float hour is a possible hour for this analysis period."""
if hour > 23 and self.is_possible_hour(0):
hour = int(hour)
if not self._is_overnight:
return self.st_time.hour <= hour <= self.end_time.hour
else:
return self.st_time.hour <= hour <= 23 or \
0 <= hour <= self.end_time.hour | [
"def",
"is_possible_hour",
"(",
"self",
",",
"hour",
")",
":",
"if",
"hour",
">",
"23",
"and",
"self",
".",
"is_possible_hour",
"(",
"0",
")",
":",
"hour",
"=",
"int",
"(",
"hour",
")",
"if",
"not",
"self",
".",
"_is_overnight",
":",
"return",
"self",
".",
"st_time",
".",
"hour",
"<=",
"hour",
"<=",
"self",
".",
"end_time",
".",
"hour",
"else",
":",
"return",
"self",
".",
"st_time",
".",
"hour",
"<=",
"hour",
"<=",
"23",
"or",
"0",
"<=",
"hour",
"<=",
"self",
".",
"end_time",
".",
"hour"
] | Check if a float hour is a possible hour for this analysis period. | [
"Check",
"if",
"a",
"float",
"hour",
"is",
"a",
"possible",
"hour",
"for",
"this",
"analysis",
"period",
"."
] | c08b7308077a48d5612f644943f92d5b5dade583 | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/analysisperiod.py#L347-L355 | train | 237,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.