id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3,200 |
Adyen/adyen-python-api-library
|
Adyen_adyen-python-api-library/Adyen/services/management/account_merchant_level_api.py
|
Adyen.services.management.account_merchant_level_api.AccountMerchantLevelApi
|
class AccountMerchantLevelApi(AdyenServiceBase):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, client=None):
super(AccountMerchantLevelApi, self).__init__(client=client)
self.service = "management"
self.baseUrl = "https://management-test.adyen.com/v3"
def create_merchant_account(self, request, idempotency_key=None, **kwargs):
"""
Create a merchant account
"""
endpoint = self.baseUrl + f"/merchants"
method = "POST"
return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs)
def get_merchant_account(self, merchantId, idempotency_key=None, **kwargs):
"""
Get a merchant account
"""
endpoint = self.baseUrl + f"/merchants/{merchantId}"
method = "GET"
return self.client.call_adyen_api(None, self.service, method, endpoint, idempotency_key, **kwargs)
def list_merchant_accounts(self, idempotency_key=None, **kwargs):
"""
Get a list of merchant accounts
"""
endpoint = self.baseUrl + f"/merchants"
method = "GET"
return self.client.call_adyen_api(None, self.service, method, endpoint, idempotency_key, **kwargs)
def request_to_activate_merchant_account(self, merchantId, idempotency_key=None, **kwargs):
"""
Request to activate a merchant account
"""
endpoint = self.baseUrl + f"/merchants/{merchantId}/activate"
method = "POST"
return self.client.call_adyen_api(None, self.service, method, endpoint, idempotency_key, **kwargs)
|
class AccountMerchantLevelApi(AdyenServiceBase):
'''NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
'''
def __init__(self, client=None):
pass
def create_merchant_account(self, request, idempotency_key=None, **kwargs):
'''
Create a merchant account
'''
pass
def get_merchant_account(self, merchantId, idempotency_key=None, **kwargs):
'''
Get a merchant account
'''
pass
def list_merchant_accounts(self, idempotency_key=None, **kwargs):
'''
Get a list of merchant accounts
'''
pass
def request_to_activate_merchant_account(self, merchantId, idempotency_key=None, **kwargs):
'''
Request to activate a merchant account
'''
pass
| 6 | 5 | 6 | 0 | 4 | 2 | 1 | 0.76 | 1 | 1 | 0 | 0 | 5 | 2 | 5 | 8 | 43 | 6 | 21 | 16 | 15 | 16 | 21 | 16 | 15 | 1 | 3 | 0 | 5 |
3,201 |
Adyen/adyen-python-api-library
|
Adyen_adyen-python-api-library/Adyen/services/management/account_company_level_api.py
|
Adyen.services.management.account_company_level_api.AccountCompanyLevelApi
|
class AccountCompanyLevelApi(AdyenServiceBase):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, client=None):
super(AccountCompanyLevelApi, self).__init__(client=client)
self.service = "management"
self.baseUrl = "https://management-test.adyen.com/v3"
def get_company_account(self, companyId, idempotency_key=None, **kwargs):
"""
Get a company account
"""
endpoint = self.baseUrl + f"/companies/{companyId}"
method = "GET"
return self.client.call_adyen_api(None, self.service, method, endpoint, idempotency_key, **kwargs)
def list_company_accounts(self, idempotency_key=None, **kwargs):
"""
Get a list of company accounts
"""
endpoint = self.baseUrl + f"/companies"
method = "GET"
return self.client.call_adyen_api(None, self.service, method, endpoint, idempotency_key, **kwargs)
def list_merchant_accounts(self, companyId, idempotency_key=None, **kwargs):
"""
Get a list of merchant accounts
"""
endpoint = self.baseUrl + f"/companies/{companyId}/merchants"
method = "GET"
return self.client.call_adyen_api(None, self.service, method, endpoint, idempotency_key, **kwargs)
|
class AccountCompanyLevelApi(AdyenServiceBase):
'''NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
'''
def __init__(self, client=None):
pass
def get_company_account(self, companyId, idempotency_key=None, **kwargs):
'''
Get a company account
'''
pass
def list_company_accounts(self, idempotency_key=None, **kwargs):
'''
Get a list of company accounts
'''
pass
def list_merchant_accounts(self, companyId, idempotency_key=None, **kwargs):
'''
Get a list of merchant accounts
'''
pass
| 5 | 4 | 6 | 0 | 4 | 2 | 1 | 0.76 | 1 | 1 | 0 | 0 | 4 | 2 | 4 | 7 | 35 | 5 | 17 | 13 | 12 | 13 | 17 | 13 | 12 | 1 | 3 | 0 | 4 |
3,202 |
AgeOfLearning/coeus-unity-python-framework
|
AgeOfLearning_coeus-unity-python-framework/tests/test_transform_ref.py
|
test_transform_ref.TransformRefTestCase
|
class TransformRefTestCase(unittest.TestCase):
def test_calculate_path(self):
menu = TransformRef("Path/To/Menu")
button = TransformRef("Button", parent=menu)
assert button.transform_path == "Button"
assert button.get_relative_transform_path() == "Button"
assert button.get_absolute_transform_path() == "Path/To/Menu/Button"
button.set_parent(None)
assert button.transform_path == "Path/To/Menu/Button"
assert button.get_relative_transform_path() == "Path/To/Menu/Button"
assert button.get_absolute_transform_path() == "Path/To/Menu/Button"
|
class TransformRefTestCase(unittest.TestCase):
def test_calculate_path(self):
pass
| 2 | 0 | 12 | 2 | 10 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 13 | 2 | 11 | 4 | 9 | 0 | 11 | 4 | 9 | 1 | 2 | 0 | 1 |
3,203 |
AgeOfLearning/coeus-unity-python-framework
|
AgeOfLearning_coeus-unity-python-framework/coeus_unity/transform.py
|
coeus_unity.transform.TransformRef
|
class TransformRef:
"""
Reference to a Unity transform with a given transform path, along with an optional sibling index that can be used
to distinguish between sibling transforms with the same path. Also contains optional references to parent and child
transforms to allow navigation of the transform hierarchy.
If the ``children`` attribute is None, it simply means that the attribute is uninitialized. The referenced
transform may or may not actually have children.
If the ``children`` attribute is an empty list, it means the referenced transform has no children.
"""
def __init__(self, transform_path, sibling_index=-1, parent=None):
"""
Initializes this TransformRef instance.
:param transform_path: Parent-relative transform path, or the absolute path if ``parent`` is None.
:param sibling_index: Optional sibling index, used to distinguish between sibling transforms with the same path.
:param parent: Optional parent transform reference.
"""
# Make sure the transform path is valid.
if not isinstance(transform_path, str):
raise ValueError("transform_path must be of type str")
# Make sure the parent transform reference is valid.
if (parent is not None) and not isinstance(parent, TransformRef):
raise ValueError("parent must be None or of type TransformRef")
# Define instance attributes.
self.id = id
self.transform_path = transform_path
self.sibling_index = sibling_index
self.children = None
self.parent = None
self.set_parent(parent)
def set_parent(self, parent):
"""
Set the parent transform reference.
:param parent: Parent transform reference.
:return: None.
"""
# Make sure the parent transform reference is valid.
if (parent is not None) and not isinstance(parent, TransformRef):
raise ValueError("parent must be None or of type TransformRef")
# Do nothing if the parent hasn't changed.
if self.parent is parent:
return
# Unset the old parent.
old_parent = self.parent
if old_parent is not None:
old_parent.remove_child(self)
# Set the new parent.
self.parent = parent
if parent is not None:
parent.add_child(self)
def add_child(self, child):
"""
Adds the child transform reference if it doesn't exist. Also converts the child's transform path to
a parent-relative path.
:param child: Child transform reference.
:return: None.
"""
# Make sure we have a valid transform reference.
if not isinstance(child, TransformRef):
raise ValueError("child must be of type TransformRef")
# Make sure we have a valid list.
if self.children is None:
self.children = []
# Add the child and update its transform path.
#
# Note that transform references with a parent use parent-relative transform paths.
if child not in self.children:
child.parent = self
child.transform_path = child.get_relative_transform_path()
self.children.append(child)
def remove_child(self, child):
"""
Removes the child transform reference if it exists. Also converts the child's transform path to
an absolute path.
:param child: Child transform reference.
:return: None.
"""
# Make sure we have a valid transform reference.
if not isinstance(child, TransformRef):
raise ValueError("child must be of type TransformRef")
# Bail if we don't have a valid list.
if self.children is None:
return
# Remove the child and update its transform path.
#
# Note that transform references without a parent use absolute transform paths.
if child in self.children:
child.transform_path = child.get_absolute_transform_path()
child.parent = None
self.children.remove(child)
def get_relative_transform_path(self):
"""
Gets the parent-relative path of the transform reference.
:return: The parent-relative transform path, if the transform reference has a parent; otherwise, the absolute
transform path.
"""
path = self.transform_path
if self.parent is not None:
path = path.split('/')[-1]
return path
def get_absolute_transform_path(self):
"""
Gets the absolute path of the transform reference by traversing its parents.
:return: The absolute transform path.
"""
path = self.transform_path
parent = self.parent
while parent is not None:
path = "{0}/{1}".format(parent.transform_path, path)
parent = parent.parent
return path
def _get_sibling_indices(self, absolute_transform_path):
"""
Constructs a list containing the sibling indices of this transform reference and all its ancestors, which is
used to distinguish between transforms with the same transform path.
Ancestor sibling indices are listed before descendants.
The number of sibling indices will match the number of sections in the transform path of this transform
reference. For example, if the transform path is "PauseMenu/ReplayButton/Text", this method will return 3
sibling indices. If there aren't enough sibling indices available, the list will be left-padded with `None`.
If all sibling indices are -1, this method will return `None` instead of a list. This shorthand not only
decreases the size of request payloads containing transform references, but also allows Unity to find the
requested transform more efficiently by using the transform path directly.
:param absolute_transform_path: Absolute transform path of the specified transform reference. This is passed
in because it was already calculated earlier.
:return: A list containing the sibling indices of this transform reference and all its ancestors.
"""
# Construct a list containing the sibling indices of this transform reference and all its ancestors.
indices = [self.sibling_index]
parent = self.parent
while parent is not None:
indices.insert(0, parent.sibling_index)
parent = parent.parent
# If all sibling indices are -1, just return None. This not only decreases the size of the request payload,
# but also allows Unity to find the requested transform more efficiently.
if indices.count(-1) == len(indices):
return None
# Make sure the number of sibling indices matches the number of elements in transform_path.
path_parts = absolute_transform_path.split('/')
while len(indices) < len(path_parts):
indices.insert(0, -1)
return indices
@staticmethod
def to_payload(transform_ref):
"""
Converts a transform reference to a request payload to be sent to the server.
The resulting payload only contains the ``transform_path`` and ``sibling_indices`` attributes since that is
sufficient to unambiguously specify transforms when sending requests to the server.
:param transform_ref: The transform reference to convert.
:return: A request payload representing the transform reference that can be sent to the server.
"""
# Bail if there's nothing to convert.
if transform_ref is None:
return None
# Make sure we have a valid transform reference to convert.
if not isinstance(transform_ref, TransformRef):
raise ValueError('transform_ref must be a type of TransformRef.')
# Convert the transform reference to a serializable payload.
#
# NOTE: Because the request payload doesn't include parent information, we need to specify the absolute
# transform path so that Unity can find the requested transform.
transform_path = transform_ref.get_absolute_transform_path()
sibling_indices = transform_ref._get_sibling_indices(transform_path)
payload = {
"transform_path": transform_path,
"sibling_indices": sibling_indices,
"children": None,
"parent": None
}
return payload
@staticmethod
def from_payload(payload, parent=None):
"""
Converts a response payload received from the server to a transform reference.
Response payloads don't include parent information, so an optional reference to a parent transform may be
specified to complete the initialization of the returned transform reference.
:param payload: The response payload to convert.
:param parent: Optional reference to a parent transform.
:return: A transform reference representing the payload that was received from the server.
"""
# Bail if there's nothing to convert.
if payload is None:
return None
# Make sure the parent transform reference is valid.
if (parent is not None) and not isinstance(parent, TransformRef):
raise ValueError("parent must be None or of type TransformRef")
# Create the transform reference.
transform_ref = TransformRef(payload['transform_path'], payload['sibling_indices'][0], parent)
# Initialize the child transform references.
if payload['children'] is not None:
transform_ref.children = []
for child_payload in payload['children']:
TransformRef.from_payload(child_payload, transform_ref)
return transform_ref
@staticmethod
def list_to_payload(transform_refs):
"""
Converts a list of transform references to a request payload to be sent to the server.
The resulting payload only contains the ``transform_path`` and ``sibling_indices`` attributes since that is
sufficient to unambiguously specify transforms when sending requests to the server.
:param transform_refs: The list of transform reference to convert.
:return: A request payload representing the transform references that can be sent to the server.
"""
# Bail if there's nothing to convert.
if transform_refs is None:
return None
# Convert the transform references to a serializable payload.
payload = []
for transform_ref in transform_refs:
transform_ref_payload = TransformRef.to_payload(transform_ref)
payload.append(transform_ref_payload)
return payload
@staticmethod
def list_from_payload(payload, parent=None):
"""
Converts a response payload received from the server to a list of transform references.
Response payloads don't include parent information, so an optional reference to a parent transform may be
specified to complete the initialization of the returned transform references.
:param payload: The response payload to convert.
:param parent: Optional reference to a parent transform.
:return: A list of transform references representing the payload that was received from the server.
"""
# Bail if there's nothing to convert.
if payload is None:
return None
# Make sure the parent transform reference is valid.
if (parent is not None) and not isinstance(parent, TransformRef):
raise ValueError("parent must be None or of type TransformRef")
# Convert the payload to a list of transform references.
transform_refs = []
for transform_ref_payload in payload:
transform_ref = TransformRef.from_payload(transform_ref_payload, parent)
transform_refs.append(transform_ref)
return transform_refs
@staticmethod
def convert_to_transform_ref(transform_ref):
"""
Converts the input to a TransformRef. If the input is already a TransformRef, no conversion is performed.
Conversion is performed to ensure backwards compatibility with commands that previously took a transform_path,
which now take a transform_ref to distinguish between multiple transforms with the same path.
:param transform_ref: an instance of TransformRef, or a string representing a transform path.
:return: If the input is already a TransformRef, no conversion is performed; otherwise, returns a new instance
of TransformRef containing the specified transform path.
"""
if not isinstance(transform_ref, TransformRef):
transform_ref = TransformRef(transform_ref)
return transform_ref
@staticmethod
def convert_to_transform_refs(transform_refs):
"""
Converts the input to an array of TransformRef. If the input is already an array of TransformRef, no conversion
is performed.
Conversion is performed to ensure backwards compatibility with commands that previously took a transform_path,
which now take a transform_ref to distinguish between multiple transforms with the same path.
:param transform_refs: an array of TransformRef, or an array of strings representing transform paths.
:return: If the input is already an array of TransformRef, no conversion is performed; otherwise, returns an
array of TransformRefs containing the specified transform paths.
"""
for i in range(len(transform_refs)):
transform_refs[i] = TransformRef.convert_to_transform_ref(transform_refs[i])
return transform_refs
|
class TransformRef:
'''
Reference to a Unity transform with a given transform path, along with an optional sibling index that can be used
to distinguish between sibling transforms with the same path. Also contains optional references to parent and child
transforms to allow navigation of the transform hierarchy.
If the ``children`` attribute is None, it simply means that the attribute is uninitialized. The referenced
transform may or may not actually have children.
If the ``children`` attribute is an empty list, it means the referenced transform has no children.
'''
def __init__(self, transform_path, sibling_index=-1, parent=None):
'''
Initializes this TransformRef instance.
:param transform_path: Parent-relative transform path, or the absolute path if ``parent`` is None.
:param sibling_index: Optional sibling index, used to distinguish between sibling transforms with the same path.
:param parent: Optional parent transform reference.
'''
pass
def set_parent(self, parent):
'''
Set the parent transform reference.
:param parent: Parent transform reference.
:return: None.
'''
pass
def add_child(self, child):
'''
Adds the child transform reference if it doesn't exist. Also converts the child's transform path to
a parent-relative path.
:param child: Child transform reference.
:return: None.
'''
pass
def remove_child(self, child):
'''
Removes the child transform reference if it exists. Also converts the child's transform path to
an absolute path.
:param child: Child transform reference.
:return: None.
'''
pass
def get_relative_transform_path(self):
'''
Gets the parent-relative path of the transform reference.
:return: The parent-relative transform path, if the transform reference has a parent; otherwise, the absolute
transform path.
'''
pass
def get_absolute_transform_path(self):
'''
Gets the absolute path of the transform reference by traversing its parents.
:return: The absolute transform path.
'''
pass
def _get_sibling_indices(self, absolute_transform_path):
'''
Constructs a list containing the sibling indices of this transform reference and all its ancestors, which is
used to distinguish between transforms with the same transform path.
Ancestor sibling indices are listed before descendants.
The number of sibling indices will match the number of sections in the transform path of this transform
reference. For example, if the transform path is "PauseMenu/ReplayButton/Text", this method will return 3
sibling indices. If there aren't enough sibling indices available, the list will be left-padded with `None`.
If all sibling indices are -1, this method will return `None` instead of a list. This shorthand not only
decreases the size of request payloads containing transform references, but also allows Unity to find the
requested transform more efficiently by using the transform path directly.
:param absolute_transform_path: Absolute transform path of the specified transform reference. This is passed
in because it was already calculated earlier.
:return: A list containing the sibling indices of this transform reference and all its ancestors.
'''
pass
@staticmethod
def to_payload(transform_ref):
'''
Converts a transform reference to a request payload to be sent to the server.
The resulting payload only contains the ``transform_path`` and ``sibling_indices`` attributes since that is
sufficient to unambiguously specify transforms when sending requests to the server.
:param transform_ref: The transform reference to convert.
:return: A request payload representing the transform reference that can be sent to the server.
'''
pass
@staticmethod
def from_payload(payload, parent=None):
'''
Converts a response payload received from the server to a transform reference.
Response payloads don't include parent information, so an optional reference to a parent transform may be
specified to complete the initialization of the returned transform reference.
:param payload: The response payload to convert.
:param parent: Optional reference to a parent transform.
:return: A transform reference representing the payload that was received from the server.
'''
pass
@staticmethod
def list_to_payload(transform_refs):
'''
Converts a list of transform references to a request payload to be sent to the server.
The resulting payload only contains the ``transform_path`` and ``sibling_indices`` attributes since that is
sufficient to unambiguously specify transforms when sending requests to the server.
:param transform_refs: The list of transform reference to convert.
:return: A request payload representing the transform references that can be sent to the server.
'''
pass
@staticmethod
def list_from_payload(payload, parent=None):
'''
Converts a response payload received from the server to a list of transform references.
Response payloads don't include parent information, so an optional reference to a parent transform may be
specified to complete the initialization of the returned transform references.
:param payload: The response payload to convert.
:param parent: Optional reference to a parent transform.
:return: A list of transform references representing the payload that was received from the server.
'''
pass
@staticmethod
def convert_to_transform_ref(transform_ref):
'''
Converts the input to a TransformRef. If the input is already a TransformRef, no conversion is performed.
Conversion is performed to ensure backwards compatibility with commands that previously took a transform_path,
which now take a transform_ref to distinguish between multiple transforms with the same path.
:param transform_ref: an instance of TransformRef, or a string representing a transform path.
:return: If the input is already a TransformRef, no conversion is performed; otherwise, returns a new instance
of TransformRef containing the specified transform path.
'''
pass
@staticmethod
def convert_to_transform_refs(transform_refs):
'''
Converts the input to an array of TransformRef. If the input is already an array of TransformRef, no conversion
is performed.
Conversion is performed to ensure backwards compatibility with commands that previously took a transform_path,
which now take a transform_ref to distinguish between multiple transforms with the same path.
:param transform_refs: an array of TransformRef, or an array of strings representing transform paths.
:return: If the input is already an array of TransformRef, no conversion is performed; otherwise, returns an
array of TransformRefs containing the specified transform paths.
'''
pass
| 20 | 14 | 23 | 4 | 9 | 10 | 3 | 1.12 | 0 | 3 | 0 | 0 | 7 | 5 | 13 | 13 | 328 | 69 | 122 | 44 | 102 | 137 | 111 | 38 | 97 | 5 | 0 | 2 | 43 |
3,204 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/portiapy/portia.py
|
portiapy.portia.EdgeDeviceSensor
|
class EdgeDeviceSensor(object):
"""Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID, a port and a sensor.
"""
def __init__(
self,
edge_device_port: EdgeDevicePort,
sensor: int,
portia_config: dict
):
"""EdgeDeviceSensor's constructor.
Arguments:
edge_device_port {EdgeDevicePort} -- instance of an Edge device
port
sensor {int} -- sensor of the device
portia_config {dict} -- Portia's configuration arguments
"""
self.edge_id = edge_device_port.edge_id
self.port = edge_device_port.port
self.sensor = sensor
self.portia_config = portia_config
def dimension(self, dimension: int) -> 'EdgeDeviceDimensionFromSensor':
"""Builds a new EdgeDeviceDimensionFromSensor instance.
Arguments:
dimension {int} -- dimension code of the device
Returns:
EdgeDeviceDimensionFromSensor -- EdgeDeviceDimensionFromSensor
instance
"""
return EdgeDeviceDimensionFromSensor(
self, dimension, self.portia_config
)
def event(self, event: int) -> 'EdgeDeviceEventFromSensor':
"""Builds a new EdgeDeviceEventFromSensor instance.
Arguments:
event {int} -- event code of the device
Returns:
EdgeDeviceEventFromSensor -- EdgeDeviceEventFromSensor instance
"""
return EdgeDeviceEventFromSensor(self, event, self.portia_config)
def dimensions(self, last: bool = False, params: dict = None) -> object:
"""Lists a device's dimensions.
Keyword Arguments:
last {bool} -- if the last package of each dimension should be
returned or not (default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the list of dimensions
"""
return add_humanize_method(describe.device_port_sensor_dimensions(
self.portia_config,
self.edge_id,
self.port,
self.sensor,
last,
params
))
def profile(
self,
strategy: 'ProfileStrategies' = profile.ProfileStrategies.BY_ZERO_PORT,
interval: int = 30,
params: dict = None
) -> dict:
"""Retrieves a sensor's profile.
Keyword Arguments:
strategy {ProfileStrategies} -- strategy to use when building the
profile (default:
{ProfileStrategies.BY_ZERO_PORT})
interval {int} -- interval of time in minutes to build the profile
(default: {30})
params {dict} -- params to send to the service (default: {None})
Returns:
dict -- dictionary with the sensor's profile
"""
return add_humanize_method(profile.sensor_profile(
self.portia_config,
self.edge_id,
self.port,
self.sensor,
strategy,
interval,
params
))
def select(self, last: bool = False, params: dict = None) -> object:
"""Retrieves a device's series by its port and sensor.
Keyword Arguments:
last {bool} -- if the last package should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's dimensions
"""
return add_humanize_method(select.query_by_port_sensor(
self.portia_config,
self.edge_id,
self.port,
self.sensor,
last,
params
))
def summary(
self,
strategy: 'SummaryStrategies' = summary.SummaryStrategies.PER_HOUR,
interval=1,
params=None
) -> object:
"""Summarizes a device by port and sensor.
Keyword Arguments:
strategy {SummaryStrategies} -- strategy to use when summarizing
(default:
{SummaryStrategies.PER_HOUR})
interval {int} -- interval of time to summarize (default: {1})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's summarized dimensions
"""
return add_humanize_method(summary.query_by_port_sensor(
self.portia_config,
self.edge_id,
self.port,
self.sensor,
strategy,
interval,
params
))
def events(self, last: bool = False, params: dict = None) -> object:
"""Retrieves a device's events by its port and sensor.
Keyword Arguments:
last {bool} -- if the last event should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's events
"""
return add_humanize_method(events.query_by_port_sensor(
self.portia_config,
self.edge_id,
self.port,
self.sensor,
last,
params
))
|
class EdgeDeviceSensor(object):
'''Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID, a port and a sensor.
'''
def __init__(
self,
edge_device_port: EdgeDevicePort,
sensor: int,
portia_config: dict
):
'''EdgeDeviceSensor's constructor.
Arguments:
edge_device_port {EdgeDevicePort} -- instance of an Edge device
port
sensor {int} -- sensor of the device
portia_config {dict} -- Portia's configuration arguments
'''
pass
def dimension(self, dimension: int) -> 'EdgeDeviceDimensionFromSensor':
'''Builds a new EdgeDeviceDimensionFromSensor instance.
Arguments:
dimension {int} -- dimension code of the device
Returns:
EdgeDeviceDimensionFromSensor -- EdgeDeviceDimensionFromSensor
instance
'''
pass
def event(self, event: int) -> 'EdgeDeviceEventFromSensor':
'''Builds a new EdgeDeviceEventFromSensor instance.
Arguments:
event {int} -- event code of the device
Returns:
EdgeDeviceEventFromSensor -- EdgeDeviceEventFromSensor instance
'''
pass
def dimensions(self, last: bool = False, params: dict = None) -> object:
'''Lists a device's dimensions.
Keyword Arguments:
last {bool} -- if the last package of each dimension should be
returned or not (default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the list of dimensions
'''
pass
def profile(
self,
strategy: 'ProfileStrategies' = profile.ProfileStrategies.BY_ZERO_PORT,
interval: int = 30,
params: dict = None
) -> dict:
'''Retrieves a sensor's profile.
Keyword Arguments:
strategy {ProfileStrategies} -- strategy to use when building the
profile (default:
{ProfileStrategies.BY_ZERO_PORT})
interval {int} -- interval of time in minutes to build the profile
(default: {30})
params {dict} -- params to send to the service (default: {None})
Returns:
dict -- dictionary with the sensor's profile
'''
pass
def select(self, last: bool = False, params: dict = None) -> object:
'''Retrieves a device's series by its port and sensor.
Keyword Arguments:
last {bool} -- if the last package should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's dimensions
'''
pass
def summary(
self,
strategy: 'SummaryStrategies' = summary.SummaryStrategies.PER_HOUR,
interval=1,
params=None
) -> object:
'''Summarizes a device by port and sensor.
Keyword Arguments:
strategy {SummaryStrategies} -- strategy to use when summarizing
(default:
{SummaryStrategies.PER_HOUR})
interval {int} -- interval of time to summarize (default: {1})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's summarized dimensions
'''
pass
def events(self, last: bool = False, params: dict = None) -> object:
'''Retrieves a device's events by its port and sensor.
Keyword Arguments:
last {bool} -- if the last event should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's events
'''
pass
| 9 | 9 | 19 | 2 | 9 | 8 | 1 | 0.92 | 1 | 6 | 3 | 0 | 8 | 4 | 8 | 8 | 164 | 22 | 74 | 28 | 50 | 68 | 20 | 13 | 11 | 1 | 1 | 0 | 8 |
3,205 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/portiapy/portia.py
|
portiapy.portia.EdgePipeline
|
class EdgePipeline(object):
"""Abstracts usage of pipeline endpoints.
"""
def __init__(self, portia_config: dict):
"""EdgePipeline's constructor.
Arguments:
portia_config {dict} -- Portia's configuration arguments
"""
self.portia_config = portia_config
def phase(self) -> 'EdgePipelinePhase':
"""Builds a new EdgePipelinePhase instance.
Returns:
EdgePipelinePhase -- EdgePipelinePhase instance
"""
return EdgePipelinePhase(self.portia_config)
def axiom(self) -> 'EdgePipelineAxiom':
"""Builds a new EdgePipelineAxiom instance.
Returns:
EdgePipelineAxiom -- EdgePipelineAxiom instance
"""
return EdgePipelineAxiom(self.portia_config)
def specification(self) -> 'EdgePipelineSpecification':
"""Builds a new EdgePipelineSpecification instance.
Returns:
EdgePipelineSpecification -- EdgePipelineSpecification instance
"""
return EdgePipelineSpecification(self.portia_config)
|
class EdgePipeline(object):
'''Abstracts usage of pipeline endpoints.
'''
def __init__(self, portia_config: dict):
'''EdgePipeline's constructor.
Arguments:
portia_config {dict} -- Portia's configuration arguments
'''
pass
def phase(self) -> 'EdgePipelinePhase':
'''Builds a new EdgePipelinePhase instance.
Returns:
EdgePipelinePhase -- EdgePipelinePhase instance
'''
pass
def axiom(self) -> 'EdgePipelineAxiom':
'''Builds a new EdgePipelineAxiom instance.
Returns:
EdgePipelineAxiom -- EdgePipelineAxiom instance
'''
pass
def specification(self) -> 'EdgePipelineSpecification':
'''Builds a new EdgePipelineSpecification instance.
Returns:
EdgePipelineSpecification -- EdgePipelineSpecification instance
'''
pass
| 5 | 5 | 7 | 1 | 2 | 4 | 1 | 2 | 1 | 4 | 3 | 0 | 4 | 1 | 4 | 4 | 34 | 7 | 9 | 6 | 4 | 18 | 9 | 6 | 4 | 1 | 1 | 0 | 4 |
3,206 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/portiapy/portia.py
|
portiapy.portia.EdgePipelineAxiom
|
class EdgePipelineAxiom(object):
"""Abstracts usage of pipeline axiom endpoints.
"""
def __init__(self, portia_config: dict):
"""EdgePipelineAxiom's constructor.
Arguments:
portia_config {dict} -- Portia's configuration arguments
"""
self.portia_config = portia_config
def list(self):
return axioms.index(self.portia_config)
def create(self, payload):
return axioms.store(self.portia_config, payload)
def display(self, axiom_name, show_params=False):
return axioms.show(self.portia_config, axiom_name, show_params)
def update(self, axiom_name, payload):
return axioms.update(self.portia_config, axiom_name, payload)
def delete(self, axiom_name):
return axioms.destroy(self.portia_config, axiom_name)
|
class EdgePipelineAxiom(object):
'''Abstracts usage of pipeline axiom endpoints.
'''
def __init__(self, portia_config: dict):
'''EdgePipelineAxiom's constructor.
Arguments:
portia_config {dict} -- Portia's configuration arguments
'''
pass
def list(self):
pass
def create(self, payload):
pass
def display(self, axiom_name, show_params=False):
pass
def update(self, axiom_name, payload):
pass
def delete(self, axiom_name):
pass
| 7 | 2 | 3 | 0 | 2 | 1 | 1 | 0.46 | 1 | 1 | 0 | 0 | 6 | 1 | 6 | 6 | 25 | 6 | 13 | 8 | 6 | 6 | 13 | 8 | 6 | 1 | 1 | 0 | 6 |
3,207 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/portiapy/portia.py
|
portiapy.portia.EdgePipelinePhase
|
class EdgePipelinePhase(object):
"""Abstracts usage of pipeline phase endpoints.
"""
def __init__(self, portia_config: dict):
"""EdgePipelinePhase's constructor.
Arguments:
portia_config {dict} -- Portia's configuration arguments
"""
self.portia_config = portia_config
def list(self) -> list:
return phases.index(self.portia_config)
def create(self, payload):
return phases.store(self.portia_config, payload)
def display(self, phase_name):
return phases.show(self.portia_config, phase_name)
def update(self, phase_name, payload):
return phases.update(self.portia_config, phase_name, payload)
|
class EdgePipelinePhase(object):
'''Abstracts usage of pipeline phase endpoints.
'''
def __init__(self, portia_config: dict):
'''EdgePipelinePhase's constructor.
Arguments:
portia_config {dict} -- Portia's configuration arguments
'''
pass
def list(self) -> list:
pass
def create(self, payload):
pass
def display(self, phase_name):
pass
def update(self, phase_name, payload):
pass
| 6 | 2 | 3 | 0 | 2 | 1 | 1 | 0.55 | 1 | 2 | 0 | 0 | 5 | 1 | 5 | 5 | 22 | 5 | 11 | 7 | 5 | 6 | 11 | 7 | 5 | 1 | 1 | 0 | 5 |
3,208 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/portiapy/portia.py
|
portiapy.portia.EdgePipelineSpecification
|
class EdgePipelineSpecification(object):
"""Abstracts usage of pipeline specification endpoints.
"""
def __init__(self, portia_config: dict):
"""EdgePipelineSpecification's constructor.
Arguments:
portia_config {dict} -- Portia's configuration arguments
"""
self.portia_config = portia_config
def list(self):
return specs.index(self.portia_config)
def create(self, payload):
return specs.store(self.portia_config, payload)
def display(self, specName):
return specs.show(self.portia_config, specName)
def update(self, specName, payload):
return specs.update(self.portia_config, specName, payload)
def delete(self, specName):
return specs.destroy(self.portia_config, specName)
|
class EdgePipelineSpecification(object):
'''Abstracts usage of pipeline specification endpoints.
'''
def __init__(self, portia_config: dict):
'''EdgePipelineSpecification's constructor.
Arguments:
portia_config {dict} -- Portia's configuration arguments
'''
pass
def list(self):
pass
def create(self, payload):
pass
def display(self, specName):
pass
def update(self, specName, payload):
pass
def delete(self, specName):
pass
| 7 | 2 | 3 | 0 | 2 | 1 | 1 | 0.46 | 1 | 1 | 0 | 0 | 6 | 1 | 6 | 6 | 25 | 6 | 13 | 8 | 6 | 6 | 13 | 8 | 6 | 1 | 1 | 0 | 6 |
3,209 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/portiapy/portia.py
|
portiapy.portia.PortiaApi
|
class PortiaApi(object):
"""A factory for devices that use our Portia API.
"""
def __init__(self, portia_config: dict):
"""PortiaApi's constructor.
Arguments:
portia_config {dict} -- Portia's configuration arguments
"""
self.portia_config = portia_config
def pipeline(self) -> 'EdgePipeline':
"""Builds a new EdgePipeline instance.
Returns:
EdgePipeline -- EdgePipeline instance
"""
return EdgePipeline(self.portia_config)
def device(self, edge_id: str) -> 'EdgeDevice':
"""Builds a new EdgeDevice instance.
Arguments:
edge_id {str} -- Edge ID that identifies the device
Returns:
EdgeDevice -- EdgeDevice instance
"""
return EdgeDevice(edge_id, self.portia_config)
|
class PortiaApi(object):
'''A factory for devices that use our Portia API.
'''
def __init__(self, portia_config: dict):
'''PortiaApi's constructor.
Arguments:
portia_config {dict} -- Portia's configuration arguments
'''
pass
def pipeline(self) -> 'EdgePipeline':
'''Builds a new EdgePipeline instance.
Returns:
EdgePipeline -- EdgePipeline instance
'''
pass
def device(self, edge_id: str) -> 'EdgeDevice':
'''Builds a new EdgeDevice instance.
Arguments:
edge_id {str} -- Edge ID that identifies the device
Returns:
EdgeDevice -- EdgeDevice instance
'''
pass
| 4 | 4 | 8 | 1 | 2 | 5 | 1 | 2.29 | 1 | 4 | 2 | 0 | 3 | 1 | 3 | 3 | 29 | 6 | 7 | 5 | 3 | 16 | 7 | 5 | 3 | 1 | 1 | 0 | 3 |
3,210 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/tests/integration/test_describe.py
|
tests.integration.test_describe.TestDescribe
|
class TestDescribe(unittest.TestCase):
"""Set of integration tests for all functions concerning the describe
module.
"""
@classmethod
def setUpClass(cls):
"""Creates a Portia configuration to test the adapter.
"""
# Settings for test
base_url = os.getenv(
'PORTIA_URL', 'https://api-portia.agriness.com/v3'
)
token = os.getenv('PORTIA_TOKEN')
# Creating portia configuration
cls.portia_config = {
'baseurl': base_url,
'authorization': token,
'debug': False,
'Accept': 'text/csv'
}
def test_device_ports(self):
ports = describe.device_ports(self.portia_config, '2DPEQ572HEXP')
self.assertListEqual(ports, [0, 1, 2, 4, 5, 6, 8, 9, 10, 11, 12, 13])
def test_device_ports_last(self):
ports = describe.device_ports(
self.portia_config, '2DPEQ572HEXP', last=True
)
self.assertListEqual(
ports['port'].tolist(), [0, 1, 2, 4, 5, 6, 8, 9, 10, 11, 12, 13]
)
self.assertListEqual(
ports['dimension_thing_code'].tolist(),
[69, 15, 15, 16, 16, 16, 22, 22, 22, 23, 68, 68]
)
def test_device_port_sensors(self):
sensors = describe.device_port_sensors(
self.portia_config, '2DPEQ572HEXP', 1
)
self.assertListEqual(sensors, [1])
def test_device_port_sensors_last(self):
sensors = describe.device_port_sensors(
self.portia_config, '2DPEQ572HEXP', 1, last=True
)
self.assertEqual(sensors.iloc[0]['sensor'], 1)
self.assertEqual(sensors.iloc[0]['dimension_code'], 1)
self.assertEqual(sensors.iloc[0]['dimension_unity_code'], 1)
self.assertEqual(sensors.iloc[0]['dimension_thing_code'], 15)
def test_device_port_dimensions(self):
dimensions = describe.device_port_dimensions(
self.portia_config, '2DPEQ572HEXP', 1
)
self.assertListEqual(dimensions, [1, 9])
def test_device_port_dimensions_last(self):
dimensions = describe.device_port_dimensions(
self.portia_config, '2DPEQ572HEXP', 1, last=True
)
self.assertEqual(dimensions.iloc[0]['sensor'], 1)
self.assertEqual(dimensions.iloc[0]['dimension_code'], 1)
self.assertEqual(dimensions.iloc[0]['dimension_thing_code'], 15)
self.assertEqual(dimensions.iloc[1]['sensor'], 1)
self.assertEqual(dimensions.iloc[1]['dimension_code'], 9)
self.assertEqual(dimensions.iloc[1]['dimension_thing_code'], 15)
def test_device_port_sensor_dimensions(self):
dimensions = describe.device_port_sensor_dimensions(
self.portia_config, '2DPEQ572HEXP', 1, 1
)
self.assertListEqual(dimensions, [1, 9])
def test_device_port_sensor_dimensions_last(self):
dimensions = describe.device_port_sensor_dimensions(
self.portia_config, '2DPEQ572HEXP', 1, 1, last=True
)
self.assertEqual(dimensions.iloc[0]['dimension_code'], 1)
self.assertEqual(dimensions.iloc[0]['dimension_unity_code'], 1)
self.assertEqual(dimensions.iloc[0]['dimension_thing_code'], 15)
self.assertEqual(dimensions.iloc[1]['dimension_code'], 9)
self.assertEqual(dimensions.iloc[1]['dimension_unity_code'], 1)
self.assertEqual(dimensions.iloc[1]['dimension_thing_code'], 15)
|
class TestDescribe(unittest.TestCase):
'''Set of integration tests for all functions concerning the describe
module.
'''
@classmethod
def setUpClass(cls):
'''Creates a Portia configuration to test the adapter.
'''
pass
def test_device_ports(self):
pass
def test_device_ports_last(self):
pass
def test_device_port_sensors(self):
pass
def test_device_port_sensors_last(self):
pass
def test_device_port_dimensions(self):
pass
def test_device_port_dimensions_last(self):
pass
def test_device_port_sensor_dimensions(self):
pass
def test_device_port_sensor_dimensions_last(self):
pass
| 11 | 2 | 9 | 1 | 8 | 0 | 1 | 0.1 | 1 | 0 | 0 | 0 | 8 | 1 | 9 | 81 | 97 | 20 | 70 | 22 | 59 | 7 | 43 | 20 | 33 | 1 | 2 | 0 | 9 |
3,211 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/tests/integration/test_events.py
|
tests.integration.test_events.TestEvents
|
class TestEvents(unittest.TestCase):
"""Set of integration tests for all functions concerning the events
module.
"""
@classmethod
def setUpClass(cls):
"""Creates a Portia configuration to test the adapter.
"""
# Settings for test
base_url = os.getenv(
'PORTIA_URL', 'https://api-portia.agriness.com/v3'
)
token = os.getenv('PORTIA_TOKEN')
# Creating portia configuration
cls.portia_config = {
'baseurl': base_url,
'authorization': token,
'debug': False,
'Accept': 'text/csv'
}
def test_query_by_port_sensor(self):
device_events = events.query_by_port_sensor(
self.portia_config, '2DPEQ572HEXP', 4, 1
)
for i, row in device_events.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
self.assertIn(row.event_code, [1, 2, 7])
def test_query_by_port_sensor_last(self):
device_events = events.query_by_port_sensor(
self.portia_config, '2DPEQ572HEXP', 4, 1, last=True
)
self.assertEqual(device_events.iloc[0].dimension_thing_code, 16)
self.assertEqual(device_events.iloc[0].dimension_unity_code, 1)
self.assertEqual(device_events.iloc[0].dimension_code, 1)
self.assertEqual(device_events.iloc[0].event_code, 1)
def test_query_by_port_dimension(self):
device_events = events.query_by_port_dimension(
self.portia_config, '2DPEQ572HEXP', 4, 1
)
for i, row in device_events.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
self.assertIn(row.event_code, [1, 2, 7])
def test_query_by_port_dimension_last(self):
device_events = events.query_by_port_dimension(
self.portia_config, '2DPEQ572HEXP', 4, 1, last=True
)
self.assertEqual(device_events.iloc[0].dimension_thing_code, 16)
self.assertEqual(device_events.iloc[0].dimension_unity_code, 1)
self.assertEqual(device_events.iloc[0].dimension_code, 1)
self.assertEqual(device_events.iloc[0].event_code, 1)
def test_query_by_port_sensor_dimension(self):
device_events = events.query_by_port_sensor_dimension(
self.portia_config, '2DPEQ572HEXP', 4, 1, 1
)
for i, row in device_events.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
self.assertIn(row.event_code, [1, 2, 7])
def test_query_by_port_sensor_dimension_last(self):
device_events = events.query_by_port_sensor_dimension(
self.portia_config, '2DPEQ572HEXP', 4, 1, 1, last=True
)
self.assertEqual(device_events.iloc[0].dimension_thing_code, 16)
self.assertEqual(device_events.iloc[0].dimension_unity_code, 1)
self.assertEqual(device_events.iloc[0].dimension_code, 1)
self.assertEqual(device_events.iloc[0].event_code, 1)
def test_query_by_port_sensor_event(self):
device_events = events.query_by_port_sensor_event(
self.portia_config, '2DPEQ572HEXP', 4, 1, 1
)
for i, row in device_events.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.event_code, 1)
def test_query_by_port_sensor_event_last(self):
device_events = events.query_by_port_sensor_event(
self.portia_config, '2DPEQ572HEXP', 4, 1, 1, last=True
)
self.assertEqual(device_events.iloc[0].dimension_thing_code, 16)
self.assertEqual(device_events.iloc[0].dimension_unity_code, 1)
self.assertEqual(device_events.iloc[0].dimension_code, 1)
self.assertEqual(device_events.iloc[0].event_code, 1)
def test_query_by_port_dimension_event(self):
device_events = events.query_by_port_dimension_event(
self.portia_config, '2DPEQ572HEXP', 4, 1, 1
)
for i, row in device_events.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.event_code, 1)
def test_query_by_port_dimension_event_last(self):
device_events = events.query_by_port_dimension_event(
self.portia_config, '2DPEQ572HEXP', 4, 1, 1, last=True
)
self.assertEqual(device_events.iloc[0].dimension_thing_code, 16)
self.assertEqual(device_events.iloc[0].dimension_unity_code, 1)
self.assertEqual(device_events.iloc[0].dimension_code, 1)
self.assertEqual(device_events.iloc[0].event_code, 1)
def test_query_by_port_sensor_dimension_event(self):
device_events = events.query_by_port_sensor_dimension_event(
self.portia_config, '2DPEQ572HEXP', 4, 1, 1, 1
)
for i, row in device_events.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.event_code, 1)
def test_query_by_port_sensor_dimension_event_last(self):
device_events = events.query_by_port_sensor_dimension_event(
self.portia_config, '2DPEQ572HEXP', 4, 1, 1, 1, last=True
)
self.assertEqual(device_events.iloc[0].dimension_thing_code, 16)
self.assertEqual(device_events.iloc[0].dimension_unity_code, 1)
self.assertEqual(device_events.iloc[0].dimension_code, 1)
self.assertEqual(device_events.iloc[0].event_code, 1)
|
class TestEvents(unittest.TestCase):
'''Set of integration tests for all functions concerning the events
module.
'''
@classmethod
def setUpClass(cls):
'''Creates a Portia configuration to test the adapter.
'''
pass
def test_query_by_port_sensor(self):
pass
def test_query_by_port_sensor_last(self):
pass
def test_query_by_port_dimension(self):
pass
def test_query_by_port_dimension_last(self):
pass
def test_query_by_port_sensor_dimension(self):
pass
def test_query_by_port_sensor_dimension_last(self):
pass
def test_query_by_port_sensor_event(self):
pass
def test_query_by_port_sensor_event_last(self):
pass
def test_query_by_port_dimension_event(self):
pass
def test_query_by_port_dimension_event_last(self):
pass
def test_query_by_port_sensor_dimension_event(self):
pass
def test_query_by_port_sensor_dimension_event_last(self):
pass
| 15 | 2 | 10 | 1 | 9 | 0 | 1 | 0.06 | 1 | 0 | 0 | 0 | 12 | 1 | 13 | 85 | 148 | 26 | 115 | 36 | 100 | 7 | 83 | 34 | 69 | 2 | 2 | 1 | 19 |
3,212 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/tests/integration/test_portia.py
|
tests.integration.test_portia.TestEdgeDevice
|
class TestEdgeDevice(unittest.TestCase):
"""Set of integration tests for all functions concerning the EdgeDevice
instance.
"""
@classmethod
def setUpClass(cls):
"""Creates a Portia configuration to test the instance.
"""
# Settings for test
base_url = os.getenv(
'PORTIA_URL', 'https://api-portia.agriness.com/v3'
)
token = os.getenv('PORTIA_TOKEN')
# Creating Portia API instance
cls.portia_api = portia.PortiaApi({
'baseurl': base_url,
'authorization': token,
'debug': False,
'Accept': 'text/csv'
})
def test_ports(self):
ports = self.portia_api.device('2DPEQ572HEXP').ports(params={
'from': None,
'to': None,
'sort': True,
'precision': 'ms',
'timezone': 'Etc/UTC'
})
self.assertListEqual(ports, [0, 1, 2, 4, 5, 8, 9, 10, 11, 12, 13])
def test_ports_last(self):
ports = self.portia_api.device('2DPEQ572HEXP').ports(
last=True,
params={
'from': None,
'to': None,
'sort': True,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
self.assertListEqual(
ports['port'].tolist(), [0, 1, 2, 4, 5, 8, 9, 10, 11, 12, 13]
)
self.assertListEqual(
ports['dimension_thing_code'].tolist(),
[69, 15, 15, 16, 16, 22, 22, 22, 23, 68, 68]
)
def test_profile(self):
device = self.portia_api.device('2DPEQ572HEXP').profile(params={
'sort': True,
'precision': 'ms',
'timezone': 'Etc/UTC'
})
self.assertEqual(device.get('device'), '2DPEQ572HEXP')
self.assertEqual(device.get('channel_id'), '1BTU7542G5EY')
self.assertEqual(device.get('channel_code'), 14)
self.assertEqual(device.get('thing_code'), 69)
self.assertEqual(len(device.get('ports')), 9)
|
class TestEdgeDevice(unittest.TestCase):
'''Set of integration tests for all functions concerning the EdgeDevice
instance.
'''
@classmethod
def setUpClass(cls):
'''Creates a Portia configuration to test the instance.
'''
pass
def test_ports(self):
pass
def test_ports_last(self):
pass
def test_profile(self):
pass
| 6 | 2 | 15 | 1 | 12 | 1 | 1 | 0.14 | 1 | 1 | 1 | 0 | 3 | 0 | 4 | 76 | 66 | 8 | 51 | 11 | 45 | 7 | 19 | 10 | 14 | 1 | 2 | 0 | 4 |
3,213 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/tests/integration/test_portia.py
|
tests.integration.test_portia.TestEdgeDeviceDimensionFromDevice
|
class TestEdgeDeviceDimensionFromDevice(unittest.TestCase):
"""Set of integration tests for all functions concerning the
EdgeDeviceDimensionFromDevice instance.
"""
@classmethod
def setUpClass(cls):
"""Creates a Portia configuration to test the instance.
"""
# Settings for test
base_url = os.getenv('PORTIA_URL', 'https://api-portia.agriness.io/v3')
token = os.getenv('PORTIA_TOKEN')
# Creating Portia API instance
cls.portia_api = portia.PortiaApi({
'baseurl': base_url,
'authorization': token,
'debug': False,
'Accept': 'text/csv'
})
def test_summary(self):
summarized_dimensions = self.portia_api.device('2DPEQ572HEXP') \
.dimension(1).summary(None, params={
'from': 1609470000000,
'to': 1609729199000,
'lower_bound': None,
'upper_bound': None,
'offset': 0,
'fill': None,
'order': None,
'limit': None,
'avg': True,
'min': True,
'max': True,
'sum': False,
'median': False,
'mode': False,
'stddev': False,
'spread': False,
'last_timestamp': False,
'precision': 'ms',
'timezone': 'Etc/UTC'
})
for i, row in summarized_dimensions.iterrows():
self.assertEqual(row.dimension_unity_code, 1)
for i, row in summarized_dimensions.humanize().iterrows():
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_unity, '°C')
|
class TestEdgeDeviceDimensionFromDevice(unittest.TestCase):
'''Set of integration tests for all functions concerning the
EdgeDeviceDimensionFromDevice instance.
'''
@classmethod
def setUpClass(cls):
'''Creates a Portia configuration to test the instance.
'''
pass
def test_summary(self):
pass
| 4 | 2 | 23 | 2 | 19 | 2 | 2 | 0.18 | 1 | 1 | 1 | 0 | 1 | 0 | 2 | 74 | 51 | 5 | 39 | 8 | 35 | 7 | 12 | 7 | 9 | 3 | 2 | 1 | 4 |
3,214 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/tests/integration/test_portia.py
|
tests.integration.test_portia.TestEdgeDeviceEventFromDimension
|
class TestEdgeDeviceEventFromDimension(unittest.TestCase):
"""Set of integration tests for all functions concerning the
EdgeDeviceEventFromDimension instance.
"""
@classmethod
def setUpClass(cls):
"""Creates a Portia configuration to test the instance.
"""
# Settings for test
base_url = os.getenv('PORTIA_URL', 'https://api-portia.agriness.io/v3')
token = os.getenv('PORTIA_TOKEN')
# Creating Portia API instance
cls.portia_api = portia.PortiaApi({
'baseurl': base_url,
'authorization': token,
'debug': False,
'Accept': 'text/csv'
})
def test_events(self):
events = self.portia_api.device('2DPEQ572HEXP').port(4).dimension(1) \
.event(1).events(params={
'from': 1609470000000,
'to': 1609729199000,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
})
for i, row in events.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.event_code, 1)
for i, row in events.humanize().iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_thing, 'Sensor_Inobram_TU')
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_unity, '°C')
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.dimension, 'Point Temperature')
self.assertEqual(row.event_code, 1)
self.assertEqual(row.event, 'Communication State')
def test_events_last(self):
events = self.portia_api.device('2DPEQ572HEXP').port(4).dimension(1) \
.event(1).events(
last=True,
params={
'from': 1609470000000,
'to': 1609729199000,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
self.assertEqual(events.iloc[0].dimension_thing_code, 16)
self.assertEqual(events.iloc[0].dimension_unity_code, 1)
self.assertEqual(events.iloc[0].dimension_code, 1)
self.assertEqual(events.iloc[0].event_code, 1)
humanized_events = events.humanize()
self.assertEqual(
humanized_events.iloc[0].dimension_thing_code, 16
)
self.assertEqual(
humanized_events.iloc[0].dimension_thing, 'Sensor_Inobram_TU'
)
self.assertEqual(
humanized_events.iloc[0].dimension_unity_code, 1
)
self.assertEqual(
humanized_events.iloc[0].dimension_unity, '°C'
)
self.assertEqual(
humanized_events.iloc[0].dimension_code, 1
)
self.assertEqual(
humanized_events.iloc[0].dimension, 'Point Temperature'
)
self.assertEqual(
humanized_events.iloc[0].event_code, 1
)
self.assertEqual(
humanized_events.iloc[0].event, 'Communication State'
)
|
class TestEdgeDeviceEventFromDimension(unittest.TestCase):
'''Set of integration tests for all functions concerning the
EdgeDeviceEventFromDimension instance.
'''
@classmethod
def setUpClass(cls):
'''Creates a Portia configuration to test the instance.
'''
pass
def test_events(self):
pass
def test_events_last(self):
pass
| 5 | 2 | 28 | 2 | 25 | 1 | 2 | 0.09 | 1 | 1 | 1 | 0 | 2 | 0 | 3 | 75 | 92 | 8 | 77 | 11 | 72 | 7 | 36 | 10 | 32 | 3 | 2 | 1 | 5 |
3,215 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/tests/integration/test_portia.py
|
tests.integration.test_portia.TestEdgeDeviceDimensionFromSensor
|
class TestEdgeDeviceDimensionFromSensor(unittest.TestCase):
"""Set of integration tests for all functions concerning the
EdgeDeviceDimensionFromSensor instance.
"""
@classmethod
def setUpClass(cls):
"""Creates a Portia configuration to test the instance.
"""
# Settings for test
base_url = os.getenv('PORTIA_URL', 'https://api-portia.agriness.io/v3')
token = os.getenv('PORTIA_TOKEN')
# Creating Portia API instance
cls.portia_api = portia.PortiaApi({
'baseurl': base_url,
'authorization': token,
'debug': False,
'Accept': 'text/csv'
})
def test_select(self):
dimensions = self.portia_api.device('2DPEQ572HEXP').port(4).sensor(1) \
.dimension(1).select(params={
'from': 1609470000000,
'to': 1609729199000,
'lower_bound': None,
'upper_bound': None,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
})
for i, row in dimensions.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
for i, row in dimensions.humanize().iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_thing, 'Sensor_Inobram_TU')
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_unity, '°C')
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.dimension, 'Point Temperature')
def test_select_last(self):
dimensions = self.portia_api.device('2DPEQ572HEXP').port(4).sensor(1) \
.dimension(1).select(
last=True,
params={
'from': 1609470000000,
'to': 1609729199000,
'lower_bound': None,
'upper_bound': None,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
self.assertEqual(dimensions.iloc[0].dimension_thing_code, 16)
self.assertEqual(dimensions.iloc[0].dimension_unity_code, 1)
self.assertEqual(dimensions.iloc[0].dimension_code, 1)
humanized_dimensions = dimensions.humanize()
self.assertEqual(
humanized_dimensions.iloc[0].dimension_thing_code, 16
)
self.assertEqual(
humanized_dimensions.iloc[0].dimension_thing, 'Sensor_Inobram_TU'
)
self.assertEqual(
humanized_dimensions.iloc[0].dimension_unity_code, 1
)
self.assertEqual(
humanized_dimensions.iloc[0].dimension_unity, '°C'
)
self.assertEqual(
humanized_dimensions.iloc[0].dimension_code, 1
)
self.assertEqual(
humanized_dimensions.iloc[0].dimension, 'Point Temperature'
)
def test_summary(self):
summarized_dimensions = self.portia_api.device('2DPEQ572HEXP') \
.port(4).sensor(1).dimension(1).summary(params={
'from': 1609470000000,
'to': 1609729199000,
'lower_bound': None,
'upper_bound': None,
'offset': 0,
'fill': None,
'order': None,
'limit': None,
'avg': True,
'min': True,
'max': True,
'sum': False,
'median': False,
'mode': False,
'stddev': False,
'spread': False,
'last_timestamp': False,
'precision': 'ms',
'timezone': 'Etc/UTC'
})
for i, row in summarized_dimensions.iterrows():
self.assertEqual(row.dimension_unity_code, 1)
for i, row in summarized_dimensions.humanize().iterrows():
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_unity, '°C')
def test_events(self):
events = self.portia_api.device('2DPEQ572HEXP').port(4).sensor(1) \
.dimension(1).events(params={
'from': 1609470000000,
'to': 1609729199000,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
})
for i, row in events.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.event_code, 1)
for i, row in events.humanize().iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_thing, 'Sensor_Inobram_TU')
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_unity, '°C')
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.dimension, 'Point Temperature')
self.assertEqual(row.event_code, 1)
self.assertEqual(row.event, 'Communication State')
def test_events_last(self):
events = self.portia_api.device('2DPEQ572HEXP').port(4).sensor(1) \
.dimension(1).events(
last=True,
params={
'from': 1609470000000,
'to': 1609729199000,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
self.assertEqual(events.iloc[0].dimension_thing_code, 16)
self.assertEqual(events.iloc[0].dimension_unity_code, 1)
self.assertEqual(events.iloc[0].dimension_code, 1)
self.assertEqual(events.iloc[0].event_code, 1)
humanized_events = events.humanize()
self.assertEqual(
humanized_events.iloc[0].dimension_thing_code, 16
)
self.assertEqual(
humanized_events.iloc[0].dimension_thing, 'Sensor_Inobram_TU'
)
self.assertEqual(
humanized_events.iloc[0].dimension_unity_code, 1
)
self.assertEqual(
humanized_events.iloc[0].dimension_unity, '°C'
)
self.assertEqual(
humanized_events.iloc[0].dimension_code, 1
)
self.assertEqual(
humanized_events.iloc[0].dimension, 'Point Temperature'
)
self.assertEqual(
humanized_events.iloc[0].event_code, 1
)
self.assertEqual(
humanized_events.iloc[0].event, 'Communication State'
)
|
class TestEdgeDeviceDimensionFromSensor(unittest.TestCase):
'''Set of integration tests for all functions concerning the
EdgeDeviceDimensionFromSensor instance.
'''
@classmethod
def setUpClass(cls):
'''Creates a Portia configuration to test the instance.
'''
pass
def test_select(self):
pass
def test_select_last(self):
pass
def test_summary(self):
pass
def test_events(self):
pass
def test_events_last(self):
pass
| 8 | 2 | 30 | 2 | 27 | 1 | 2 | 0.04 | 1 | 1 | 1 | 0 | 5 | 0 | 6 | 78 | 189 | 17 | 165 | 20 | 157 | 7 | 68 | 19 | 61 | 3 | 2 | 1 | 12 |
3,216 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/portiapy/portia.py
|
portiapy.portia.EdgeDevicePort
|
class EdgeDevicePort(object):
"""Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID and a port.
"""
def __init__(
self, edge_device: EdgeDevice, port: int, portia_config: dict
):
"""EdgeDevicePort's constructor.
Arguments:
edge_device {EdgeDevice} -- instance of an Edge device
port {int} -- port of the device
portia_config {dict} -- Portia's configuration arguments
"""
self.edge_id = edge_device.edge_id
self.port = port
self.portia_config = portia_config
def sensor(self, sensor: int) -> 'EdgeDeviceSensor':
"""Builds a new EdgeDeviceSensor instance.
Arguments:
sensor {int} -- sensor of the device
Returns:
EdgeDeviceSensor -- EdgeDeviceSensor instance
"""
return EdgeDeviceSensor(self, sensor, self.portia_config)
def dimension(self, dimension: int) -> 'EdgeDeviceDimensionFromPort':
"""Builds a new EdgeDeviceDimensionFromPort instance.
Arguments:
dimension {int} -- dimension code of the device
Returns:
EdgeDeviceDimensionFromPort -- EdgeDeviceDimensionFromPort instance
"""
return EdgeDeviceDimensionFromPort(self, dimension, self.portia_config)
def sensors(self, last: bool = False, params: dict = None) -> object:
"""Lists a device's sensors.
Keyword Arguments:
last {bool} -- if the last package of each sensor should be
returned or not (default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the list of sensors
"""
return add_humanize_method(describe.device_port_sensors(
self.portia_config, self.edge_id, self.port, last, params
))
def dimensions(self, last: bool = False, params: dict = None) -> object:
"""Lists a device's dimensions.
Keyword Arguments:
last {bool} -- if the last package of each dimension should be
returned or not (default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the list of dimensions
"""
return add_humanize_method(describe.device_port_dimensions(
self.portia_config, self.edge_id, self.port, last, params
))
def profile(
self,
strategy: 'ProfileStrategies' = profile.ProfileStrategies.BY_ZERO_PORT,
interval: int = 30,
params: dict = None
) -> dict:
"""Retrieves a port's profile.
Keyword Arguments:
strategy {ProfileStrategies} -- strategy to use when building the
profile (default:
{ProfileStrategies.BY_ZERO_PORT})
interval {int} -- interval of time in minutes to build the profile
(default: {30})
params {dict} -- params to send to the service (default: {None})
Returns:
dict -- dictionary with the port's profile
"""
return add_humanize_method(profile.port_profile(
self.portia_config,
self.edge_id,
self.port,
strategy,
interval,
params
))
|
class EdgeDevicePort(object):
'''Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID and a port.
'''
def __init__(
self, edge_device: EdgeDevice, port: int, portia_config: dict
):
'''EdgeDevicePort's constructor.
Arguments:
edge_device {EdgeDevice} -- instance of an Edge device
port {int} -- port of the device
portia_config {dict} -- Portia's configuration arguments
'''
pass
def sensor(self, sensor: int) -> 'EdgeDeviceSensor':
'''Builds a new EdgeDeviceSensor instance.
Arguments:
sensor {int} -- sensor of the device
Returns:
EdgeDeviceSensor -- EdgeDeviceSensor instance
'''
pass
def dimension(self, dimension: int) -> 'EdgeDeviceDimensionFromPort':
'''Builds a new EdgeDeviceDimensionFromPort instance.
Arguments:
dimension {int} -- dimension code of the device
Returns:
EdgeDeviceDimensionFromPort -- EdgeDeviceDimensionFromPort instance
'''
pass
def sensors(self, last: bool = False, params: dict = None) -> object:
'''Lists a device's sensors.
Keyword Arguments:
last {bool} -- if the last package of each sensor should be
returned or not (default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the list of sensors
'''
pass
def dimensions(self, last: bool = False, params: dict = None) -> object:
'''Lists a device's dimensions.
Keyword Arguments:
last {bool} -- if the last package of each dimension should be
returned or not (default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the list of dimensions
'''
pass
def profile(
self,
strategy: 'ProfileStrategies' = profile.ProfileStrategies.BY_ZERO_PORT,
interval: int = 30,
params: dict = None
) -> dict:
'''Retrieves a port's profile.
Keyword Arguments:
strategy {ProfileStrategies} -- strategy to use when building the
profile (default:
{ProfileStrategies.BY_ZERO_PORT})
interval {int} -- interval of time in minutes to build the profile
(default: {30})
params {dict} -- params to send to the service (default: {None})
Returns:
dict -- dictionary with the port's profile
'''
pass
| 7 | 7 | 15 | 2 | 5 | 8 | 1 | 1.45 | 1 | 6 | 3 | 0 | 6 | 3 | 6 | 6 | 97 | 16 | 33 | 17 | 19 | 48 | 15 | 10 | 8 | 1 | 1 | 0 | 6 |
3,217 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/tests/integration/test_portia.py
|
tests.integration.test_portia.TestEdgeDeviceEventFromSensor
|
class TestEdgeDeviceEventFromSensor(unittest.TestCase):
"""Set of integration tests for all functions concerning the
EdgeDeviceEventFromSensor instance.
"""
@classmethod
def setUpClass(cls):
"""Creates a Portia configuration to test the instance.
"""
# Settings for test
base_url = os.getenv('PORTIA_URL', 'https://api-portia.agriness.io/v3')
token = os.getenv('PORTIA_TOKEN')
# Creating Portia API instance
cls.portia_api = portia.PortiaApi({
'baseurl': base_url,
'authorization': token,
'debug': False,
'Accept': 'text/csv'
})
def test_events(self):
events = self.portia_api.device('2DPEQ572HEXP').port(4).sensor(1) \
.event(1).events(params={
'from': 1609470000000,
'to': 1609729199000,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
})
for i, row in events.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.event_code, 1)
for i, row in events.humanize().iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_thing, 'Sensor_Inobram_TU')
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_unity, '°C')
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.dimension, 'Point Temperature')
self.assertEqual(row.event_code, 1)
self.assertEqual(row.event, 'Communication State')
def test_events_last(self):
events = self.portia_api.device('2DPEQ572HEXP').port(4).sensor(1) \
.event(1).events(
last=True,
params={
'from': 1609470000000,
'to': 1609729199000,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
self.assertEqual(events.iloc[0].dimension_thing_code, 16)
self.assertEqual(events.iloc[0].dimension_unity_code, 1)
self.assertEqual(events.iloc[0].dimension_code, 1)
self.assertEqual(events.iloc[0].event_code, 1)
humanized_events = events.humanize()
self.assertEqual(
humanized_events.iloc[0].dimension_thing_code, 16
)
self.assertEqual(
humanized_events.iloc[0].dimension_thing, 'Sensor_Inobram_TU'
)
self.assertEqual(
humanized_events.iloc[0].dimension_unity_code, 1
)
self.assertEqual(
humanized_events.iloc[0].dimension_unity, '°C'
)
self.assertEqual(
humanized_events.iloc[0].dimension_code, 1
)
self.assertEqual(
humanized_events.iloc[0].dimension, 'Point Temperature'
)
self.assertEqual(
humanized_events.iloc[0].event_code, 1
)
self.assertEqual(
humanized_events.iloc[0].event, 'Communication State'
)
|
class TestEdgeDeviceEventFromSensor(unittest.TestCase):
'''Set of integration tests for all functions concerning the
EdgeDeviceEventFromSensor instance.
'''
@classmethod
def setUpClass(cls):
'''Creates a Portia configuration to test the instance.
'''
pass
def test_events(self):
pass
def test_events_last(self):
pass
| 5 | 2 | 28 | 2 | 25 | 1 | 2 | 0.09 | 1 | 1 | 1 | 0 | 2 | 0 | 3 | 75 | 92 | 8 | 77 | 11 | 72 | 7 | 36 | 10 | 32 | 3 | 2 | 1 | 5 |
3,218 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/tests/integration/test_portia.py
|
tests.integration.test_portia.TestEdgeDevicePort
|
class TestEdgeDevicePort(unittest.TestCase):
"""Set of integration tests for all functions concerning the EdgeDevicePort
instance.
"""
@classmethod
def setUpClass(cls):
"""Creates a Portia configuration to test the instance.
"""
# Settings for test
base_url = os.getenv('PORTIA_URL', 'https://api-portia.agriness.io/v3')
token = os.getenv('PORTIA_TOKEN')
# Creating Portia API instance
cls.portia_api = portia.PortiaApi({
'baseurl': base_url,
'authorization': token,
'debug': False,
'Accept': 'text/csv'
})
def test_sensors(self):
sensors = self.portia_api.device('2DPEQ572HEXP').port(1).sensors(
params={
'from': None,
'to': None,
'sort': True,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
self.assertListEqual(sensors, [1])
def test_sensors_last(self):
sensors = self.portia_api.device('2DPEQ572HEXP').port(1).sensors(
last=True,
params={
'from': None,
'to': None,
'sort': True,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
self.assertEqual(sensors.iloc[0]['sensor'], 1)
self.assertEqual(sensors.iloc[0]['dimension_code'], 1)
self.assertEqual(sensors.iloc[0]['dimension_unity_code'], 1)
self.assertEqual(sensors.iloc[0]['dimension_thing_code'], 15)
humanized_sensors = sensors.humanize()
self.assertEqual(humanized_sensors.iloc[0]['sensor'], 1)
self.assertEqual(
humanized_sensors.iloc[0]['dimension_code'], 1
)
self.assertEqual(
humanized_sensors.iloc[0]['dimension'], 'Point Temperature'
)
self.assertEqual(
humanized_sensors.iloc[0]['dimension_unity_code'], 1
)
self.assertEqual(
humanized_sensors.iloc[0]['dimension_unity'], '°C'
)
self.assertEqual(
humanized_sensors.iloc[0]['dimension_thing_code'], 15
)
self.assertEqual(
humanized_sensors.iloc[0]['dimension_thing'], 'Sensor_Inobram_T'
)
def test_dimensions(self):
dimensions = self.portia_api.device('2DPEQ572HEXP').port(1).dimensions(
params={
'from': None,
'to': None,
'sort': True,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
self.assertListEqual(dimensions, [1, 9])
def test_dimensions_last(self):
dimensions = self.portia_api.device('2DPEQ572HEXP').port(1).dimensions(
last=True,
params={
'from': None,
'to': None,
'sort': True,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
self.assertEqual(dimensions.iloc[0]['sensor'], 1)
self.assertEqual(dimensions.iloc[0]['dimension_code'], 1)
self.assertEqual(dimensions.iloc[0]['dimension_thing_code'], 15)
self.assertEqual(dimensions.iloc[1]['sensor'], 1)
self.assertEqual(dimensions.iloc[1]['dimension_code'], 9)
self.assertEqual(dimensions.iloc[1]['dimension_thing_code'], 15)
humanized_dimensions = dimensions.humanize()
self.assertEqual(humanized_dimensions.iloc[0]['sensor'], 1)
self.assertEqual(
humanized_dimensions.iloc[0]['dimension_code'], 1
)
self.assertEqual(
humanized_dimensions.iloc[0]['dimension'], 'Point Temperature'
)
self.assertEqual(
humanized_dimensions.iloc[0]['dimension_thing_code'], 15
)
self.assertEqual(
humanized_dimensions.iloc[0]['dimension_thing'], 'Sensor_Inobram_T'
)
self.assertEqual(humanized_dimensions.iloc[1]['sensor'], 1)
self.assertEqual(
humanized_dimensions.iloc[1]['dimension_code'], 9
)
self.assertEqual(
humanized_dimensions.iloc[1]['dimension'],
'Point Water Temperature'
)
self.assertEqual(
humanized_dimensions.iloc[1]['dimension_thing_code'], 15
)
self.assertEqual(
humanized_dimensions.iloc[1]['dimension_thing'], 'Sensor_Inobram_T'
)
def test_profile(self):
port = self.portia_api.device('2DPEQ572HEXP').port(4).profile(params={
'sort': True,
'precision': 'ms',
'timezone': 'Etc/UTC'
})
self.assertEqual(port.get('device'), '2DPEQ572HEXP')
self.assertEqual(port.get('channel_id'), '1BTU7542G5EY')
self.assertEqual(port.get('channel_code'), 14)
self.assertEqual(port.get('thing_code'), 69)
self.assertEqual(len(port.get('ports')), 1)
self.assertEqual(len(port.get('ports')[0].get('sensors')), 2)
|
class TestEdgeDevicePort(unittest.TestCase):
'''Set of integration tests for all functions concerning the EdgeDevicePort
instance.
'''
@classmethod
def setUpClass(cls):
'''Creates a Portia configuration to test the instance.
'''
pass
def test_sensors(self):
pass
def test_sensors_last(self):
pass
def test_dimensions(self):
pass
def test_dimensions_last(self):
pass
def test_profile(self):
pass
| 8 | 2 | 23 | 2 | 21 | 1 | 1 | 0.06 | 1 | 1 | 1 | 0 | 5 | 0 | 6 | 78 | 146 | 14 | 125 | 17 | 117 | 7 | 52 | 16 | 45 | 1 | 2 | 0 | 6 |
3,219 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/tests/integration/test_portia.py
|
tests.integration.test_portia.TestEdgeDeviceSensor
|
class TestEdgeDeviceSensor(unittest.TestCase):
"""Set of integration tests for all functions concerning the
EdgeDeviceSensor instance.
"""
@classmethod
def setUpClass(cls):
"""Creates a Portia configuration to test the instance.
"""
# Settings for test
base_url = os.getenv('PORTIA_URL', 'https://api-portia.agriness.io/v3')
token = os.getenv('PORTIA_TOKEN')
# Creating Portia API instance
cls.portia_api = portia.PortiaApi({
'baseurl': base_url,
'authorization': token,
'debug': False,
'Accept': 'text/csv'
})
def test_dimensions(self):
dimensions = self.portia_api.device('2DPEQ572HEXP').port(1).sensor(1) \
.dimensions(
params={
'from': None,
'to': None,
'sort': True,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
self.assertListEqual(dimensions, [1, 9])
def test_dimensions_last(self):
dimensions = self.portia_api.device('2DPEQ572HEXP').port(1).sensor(1) \
.dimensions(
last=True,
params={
'from': None,
'to': None,
'sort': True,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
self.assertEqual(dimensions.iloc[0]['dimension_code'], 1)
self.assertEqual(dimensions.iloc[0]['dimension_unity_code'], 1)
self.assertEqual(dimensions.iloc[0]['dimension_thing_code'], 15)
self.assertEqual(dimensions.iloc[1]['dimension_code'], 9)
self.assertEqual(dimensions.iloc[1]['dimension_unity_code'], 1)
self.assertEqual(dimensions.iloc[1]['dimension_thing_code'], 15)
humanized_dimensions = dimensions.humanize()
self.assertEqual(
humanized_dimensions.iloc[0]['dimension_code'], 1
)
self.assertEqual(
humanized_dimensions.iloc[0]['dimension'], 'Point Temperature'
)
self.assertEqual(
humanized_dimensions.iloc[0]['dimension_unity_code'], 1
)
self.assertEqual(
humanized_dimensions.iloc[0]['dimension_unity'], '°C'
)
self.assertEqual(
humanized_dimensions.iloc[0]['dimension_thing_code'], 15
)
self.assertEqual(
humanized_dimensions.iloc[0]['dimension_thing'], 'Sensor_Inobram_T'
)
self.assertEqual(
humanized_dimensions.iloc[1]['dimension_code'], 9
)
self.assertEqual(
humanized_dimensions.iloc[1]['dimension'],
'Point Water Temperature'
)
self.assertEqual(
humanized_dimensions.iloc[1]['dimension_unity_code'], 1
)
self.assertEqual(
humanized_dimensions.iloc[1]['dimension_unity'], '°C'
)
self.assertEqual(
humanized_dimensions.iloc[1]['dimension_thing_code'], 15
)
self.assertEqual(
humanized_dimensions.iloc[1]['dimension_thing'], 'Sensor_Inobram_T'
)
def test_profile(self):
sensor = self.portia_api.device('2DPEQ572HEXP').port(4).sensor(1). \
profile(params={
'sort': True,
'precision': 'ms',
'timezone': 'Etc/UTC'
})
self.assertEqual(sensor.get('device'), '2DPEQ572HEXP')
self.assertEqual(sensor.get('channel_id'), '1BTU7542G5EY')
self.assertEqual(sensor.get('channel_code'), 14)
self.assertEqual(sensor.get('thing_code'), 69)
self.assertEqual(len(sensor.get('ports')), 1)
self.assertEqual(len(sensor.get('ports')[0].get('sensors')), 1)
def test_select(self):
dimensions = self.portia_api.device('2DPEQ572HEXP').port(4) \
.sensor(1).select(params={
'from': 1609470000000,
'to': 1609729199000,
'lower_bound': None,
'upper_bound': None,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
})
for i, row in dimensions.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
for i, row in dimensions.humanize().iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_thing, 'Sensor_Inobram_TU')
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_unity, '°C')
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.dimension, 'Point Temperature')
def test_select_last(self):
dimensions = self.portia_api.device('2DPEQ572HEXP').port(4) \
.sensor(1).select(
last=True,
params={
'from': 1609470000000,
'to': 1609729199000,
'lower_bound': None,
'upper_bound': None,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
self.assertEqual(dimensions.iloc[0].dimension_thing_code, 16)
self.assertEqual(dimensions.iloc[0].dimension_unity_code, 1)
self.assertEqual(dimensions.iloc[0].dimension_code, 1)
humanized_dimensions = dimensions.humanize()
self.assertEqual(
humanized_dimensions.iloc[0].dimension_thing_code, 16
)
self.assertEqual(
humanized_dimensions.iloc[0].dimension_thing, 'Sensor_Inobram_TU'
)
self.assertEqual(
humanized_dimensions.iloc[0].dimension_unity_code, 1
)
self.assertEqual(
humanized_dimensions.iloc[0].dimension_unity, '°C'
)
self.assertEqual(
humanized_dimensions.iloc[0].dimension_code, 1
)
self.assertEqual(
humanized_dimensions.iloc[0].dimension, 'Point Temperature'
)
def test_summary(self):
summarized_dimensions = self.portia_api.device('2DPEQ572HEXP') \
.port(4).sensor(1).summary(params={
'from': 1609470000000,
'to': 1609729199000,
'lower_bound': None,
'upper_bound': None,
'offset': 0,
'fill': None,
'order': None,
'limit': None,
'avg': True,
'min': True,
'max': True,
'sum': False,
'median': False,
'mode': False,
'stddev': False,
'spread': False,
'last_timestamp': False,
'precision': 'ms',
'timezone': 'Etc/UTC'
})
for i, row in summarized_dimensions.iterrows():
self.assertEqual(row.dimension_unity_code, 1)
for i, row in summarized_dimensions.humanize().iterrows():
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_unity, '°C')
def test_events(self):
events = self.portia_api.device('2DPEQ572HEXP').port(4) \
.sensor(1).events(params={
'from': 1609470000000,
'to': 1609729199000,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
})
for i, row in events.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.event_code, 1)
for i, row in events.humanize().iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_thing, 'Sensor_Inobram_TU')
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_unity, '°C')
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.dimension, 'Point Temperature')
self.assertEqual(row.event_code, 1)
self.assertEqual(row.event, 'Communication State')
def test_events_last(self):
events = self.portia_api.device('2DPEQ572HEXP').port(4) \
.sensor(1).events(
last=True,
params={
'from': 1609470000000,
'to': 1609729199000,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
self.assertEqual(events.iloc[0].dimension_thing_code, 16)
self.assertEqual(events.iloc[0].dimension_unity_code, 1)
self.assertEqual(events.iloc[0].dimension_code, 1)
self.assertEqual(events.iloc[0].event_code, 1)
humanized_events = events.humanize()
self.assertEqual(
humanized_events.iloc[0].dimension_thing_code, 16
)
self.assertEqual(
humanized_events.iloc[0].dimension_thing, 'Sensor_Inobram_TU'
)
self.assertEqual(
humanized_events.iloc[0].dimension_unity_code, 1
)
self.assertEqual(
humanized_events.iloc[0].dimension_unity, '°C'
)
self.assertEqual(
humanized_events.iloc[0].dimension_code, 1
)
self.assertEqual(
humanized_events.iloc[0].dimension, 'Point Temperature'
)
self.assertEqual(
humanized_events.iloc[0].event_code, 1
)
self.assertEqual(
humanized_events.iloc[0].event, 'Communication State'
)
|
class TestEdgeDeviceSensor(unittest.TestCase):
'''Set of integration tests for all functions concerning the
EdgeDeviceSensor instance.
'''
@classmethod
def setUpClass(cls):
'''Creates a Portia configuration to test the instance.
'''
pass
def test_dimensions(self):
pass
def test_dimensions_last(self):
pass
def test_profile(self):
pass
def test_select(self):
pass
def test_select_last(self):
pass
def test_summary(self):
pass
def test_events(self):
pass
def test_events_last(self):
pass
| 11 | 2 | 29 | 2 | 27 | 0 | 2 | 0.03 | 1 | 1 | 1 | 0 | 8 | 0 | 9 | 81 | 278 | 25 | 246 | 27 | 235 | 7 | 100 | 26 | 90 | 3 | 2 | 1 | 15 |
3,220 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/tests/integration/test_select.py
|
tests.integration.test_select.TestSelect
|
class TestSelect(unittest.TestCase):
"""Set of integration tests for all functions concerning the select
module.
"""
@classmethod
def setUpClass(cls):
"""Creates a Portia configuration to test the adapter.
"""
# Settings for test
base_url = os.getenv(
'PORTIA_URL', 'https://api-portia.agriness.com/v3'
)
token = os.getenv('PORTIA_TOKEN')
# Creating portia configuration
cls.portia_config = {
'baseurl': base_url,
'authorization': token,
'debug': False,
'Accept': 'text/csv'
}
def test_query_by_port_sensor(self):
dimensions = select.query_by_port_sensor(
self.portia_config, '2DPEQ572HEXP', 4, 1
)
for i, row in dimensions.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
def test_query_by_port_sensor_last(self):
dimensions = select.query_by_port_sensor(
self.portia_config, '2DPEQ572HEXP', 4, 1, last=True
)
self.assertEqual(dimensions.iloc[0].dimension_thing_code, 16)
self.assertEqual(dimensions.iloc[0].dimension_unity_code, 1)
self.assertEqual(dimensions.iloc[0].dimension_code, 1)
def test_query_by_port_dimension(self):
dimensions = select.query_by_port_dimension(
self.portia_config, '2DPEQ572HEXP', 4, 1
)
for i, row in dimensions.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
def test_query_by_port_dimension_last(self):
dimensions = select.query_by_port_dimension(
self.portia_config, '2DPEQ572HEXP', 4, 1, last=True
)
self.assertEqual(dimensions.iloc[0].dimension_thing_code, 16)
self.assertEqual(dimensions.iloc[0].dimension_unity_code, 1)
self.assertEqual(dimensions.iloc[0].dimension_code, 1)
def test_query_by_port_sensor_dimension(self):
dimensions = select.query_by_port_sensor_dimension(
self.portia_config, '2DPEQ572HEXP', 4, 1, 1
)
for i, row in dimensions.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
def test_query_by_port_sensor_dimension_last(self):
dimensions = select.query_by_port_sensor_dimension(
self.portia_config, '2DPEQ572HEXP', 4, 1, 1, last=True
)
self.assertEqual(dimensions.iloc[0].dimension_thing_code, 16)
self.assertEqual(dimensions.iloc[0].dimension_unity_code, 1)
self.assertEqual(dimensions.iloc[0].dimension_code, 1)
|
class TestSelect(unittest.TestCase):
'''Set of integration tests for all functions concerning the select
module.
'''
@classmethod
def setUpClass(cls):
'''Creates a Portia configuration to test the adapter.
'''
pass
def test_query_by_port_sensor(self):
pass
def test_query_by_port_sensor_last(self):
pass
def test_query_by_port_dimension(self):
pass
def test_query_by_port_dimension_last(self):
pass
def test_query_by_port_sensor_dimension(self):
pass
def test_query_by_port_sensor_dimension_last(self):
pass
| 9 | 2 | 10 | 1 | 8 | 1 | 1 | 0.12 | 1 | 0 | 0 | 0 | 6 | 1 | 7 | 79 | 79 | 14 | 58 | 21 | 49 | 7 | 38 | 19 | 30 | 2 | 2 | 1 | 10 |
3,221 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/tests/integration/test_summary.py
|
tests.integration.test_summary.TestSummary
|
class TestSummary(unittest.TestCase):
"""Set of integration tests for all functions concerning the summary
module.
"""
@classmethod
def setUpClass(cls):
"""Creates a Portia configuration to test the adapter.
"""
# Settings for test
base_url = os.getenv(
'PORTIA_URL', 'https://api-portia.agriness.com/v3'
)
token = os.getenv('PORTIA_TOKEN')
# Creating portia configuration
cls.portia_config = {
'baseurl': base_url,
'authorization': token,
'debug': False,
'Accept': 'text/csv'
}
def test_summary_strategies(self):
per_minute = summary.SummaryStrategies.PER_MINUTE
per_hour = summary.SummaryStrategies.PER_HOUR
per_day = summary.SummaryStrategies.PER_DAY
per_month = summary.SummaryStrategies.PER_MONTH
per_year = summary.SummaryStrategies.PER_YEAR
self.assertEqual(per_minute.endpoint, 'perminute')
self.assertEqual(per_hour.endpoint, 'perhour')
self.assertEqual(per_day.endpoint, 'perday')
self.assertEqual(per_month.endpoint, 'permonth')
self.assertEqual(per_year.endpoint, 'peryear')
def test_query_by_dimension(self):
summarized_dimensions = summary.query_by_dimension(
self.portia_config,
1,
[{
'device': '2DPEQ572HEXP'
}, {
'device': '3WPH414SRSTZ'
}],
strategy=summary.SummaryStrategies.PER_DAY,
params={
'from': 1609470000000,
'to': 1609729199000,
'lower_bound': None,
'upper_bound': None,
'offset': 0,
'fill': None,
'order': None,
'limit': None,
'avg': True,
'min': True,
'max': True,
'sum': False,
'median': False,
'mode': False,
'stddev': False,
'spread': False,
'last_timestamp': False,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
for i, row in summarized_dimensions.iterrows():
self.assertEqual(row.dimension_unity_code, 1)
def test_query_device_by_dimension(self):
summarized_dimensions = summary.query_device_by_dimension(
self.portia_config,
'2DPEQ572HEXP',
1,
None,
strategy=summary.SummaryStrategies.PER_DAY,
params={
'from': 1609470000000,
'to': 1609729199000,
'lower_bound': None,
'upper_bound': None,
'offset': 0,
'fill': None,
'order': None,
'limit': None,
'avg': True,
'min': True,
'max': True,
'sum': False,
'median': False,
'mode': False,
'stddev': False,
'spread': False,
'last_timestamp': False,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
for i, row in summarized_dimensions.iterrows():
self.assertEqual(row.dimension_unity_code, 1)
def test_query_by_port_sensor(self):
summarized_dimensions = summary.query_by_port_sensor(
self.portia_config,
'2DPEQ572HEXP',
4,
1,
strategy=summary.SummaryStrategies.PER_DAY,
params={
'from': 1609470000000,
'to': 1609729199000,
'lower_bound': None,
'upper_bound': None,
'offset': 0,
'fill': None,
'order': None,
'limit': None,
'avg': True,
'min': True,
'max': True,
'sum': False,
'median': False,
'mode': False,
'stddev': False,
'spread': False,
'last_timestamp': False,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
for i, row in summarized_dimensions.iterrows():
self.assertEqual(row.dimension_unity_code, 1)
def test_query_by_port_sensor_dimension(self):
summarized_dimensions = summary.query_by_port_sensor_dimension(
self.portia_config,
'2DPEQ572HEXP',
4,
1,
1,
strategy=summary.SummaryStrategies.PER_DAY,
params={
'from': 1609470000000,
'to': 1609729199000,
'lower_bound': None,
'upper_bound': None,
'offset': 0,
'fill': None,
'order': None,
'limit': None,
'avg': True,
'min': True,
'max': True,
'sum': False,
'median': False,
'mode': False,
'stddev': False,
'spread': False,
'last_timestamp': False,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
for i, row in summarized_dimensions.iterrows():
self.assertEqual(row.dimension_unity_code, 1)
|
class TestSummary(unittest.TestCase):
'''Set of integration tests for all functions concerning the summary
module.
'''
@classmethod
def setUpClass(cls):
'''Creates a Portia configuration to test the adapter.
'''
pass
def test_summary_strategies(self):
pass
def test_query_by_dimension(self):
pass
def test_query_device_by_dimension(self):
pass
def test_query_by_port_sensor(self):
pass
def test_query_by_port_sensor_dimension(self):
pass
| 8 | 2 | 27 | 1 | 25 | 1 | 2 | 0.05 | 1 | 1 | 1 | 0 | 5 | 1 | 6 | 78 | 171 | 12 | 152 | 24 | 144 | 7 | 32 | 22 | 25 | 2 | 2 | 1 | 10 |
3,222 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/tests/unit/test_utils.py
|
tests.unit.test_utils.TestHumanization
|
class TestHumanization(unittest.TestCase):
"""Set of unit tests for all functions concerning humanization of data.
"""
def test_humanize_thing_code(self):
h_thing_code = utils.humanize_thing_code(1)
self.assertEqual(h_thing_code, 'Sensor_Agriness_TU')
def test_humanize_dimension_code(self):
h_dimension_code = utils.humanize_dimension_code(1)
self.assertEqual(h_dimension_code, 'Point Temperature')
h_dimension_code = utils.humanize_dimension_code(1, 'pt-br')
self.assertEqual(h_dimension_code, 'Temperatura Pontual')
h_dimension_code = utils.humanize_dimension_code(1, custom={
'en-us': {1: 'Temperatura Pontual de Teste'}
})
self.assertEqual(h_dimension_code, 'Temperatura Pontual de Teste')
def test_humanize_event_code(self):
h_dimension_code = utils.humanize_event_code(1)
self.assertEqual(h_dimension_code, 'Communication State')
h_dimension_code = utils.humanize_event_code(1, 'pt-br')
self.assertEqual(h_dimension_code, 'Estado de Comunicação')
h_dimension_code = utils.humanize_event_code(1, custom={
'en-us': {1: 'Status de Comunicação'}
})
self.assertEqual(h_dimension_code, 'Status de Comunicação')
def test_humanize_unity_code(self):
h_dimension_code = utils.humanize_unity_code(1)
self.assertEqual(h_dimension_code, '°C')
h_dimension_code = utils.humanize_unity_code(1, 'pt-br')
self.assertEqual(h_dimension_code, '°C')
h_dimension_code = utils.humanize_unity_code(1, custom={
'en-us': {1: 'Celsius'}
})
self.assertEqual(h_dimension_code, 'Celsius')
def test_humanize_dataframe(self):
dataframe = pd.DataFrame(data=[{
'header_timestamp': 1565634220016,
'event_value': 'ON',
'dimension_code': 1,
'event_code': 1,
'dimension_unity_code': 1,
'dimension_thing_code': 15
}, {
'header_timestamp': 1565634165295,
'event_value': 'OFF',
'dimension_code': 3,
'event_code': 1,
'dimension_unity_code': 2,
'dimension_thing_code': 16
}])
h_dataframe = utils.humanize_dataframe(dataframe)
self.assertIn('header_timestamp', h_dataframe.columns)
self.assertIn('event_value', h_dataframe.columns)
self.assertIn('dimension_code', h_dataframe.columns)
self.assertIn('event_code', h_dataframe.columns)
self.assertIn('dimension_unity_code', h_dataframe.columns)
self.assertIn('dimension_thing_code', h_dataframe.columns)
self.assertIn('dimension_thing', h_dataframe.columns)
self.assertIn('dimension', h_dataframe.columns)
self.assertIn('event', h_dataframe.columns)
self.assertIn('dimension_unity', h_dataframe.columns)
self.assertEqual(
h_dataframe.iloc[0].get('dimension_thing'), 'Sensor_Inobram_T'
)
self.assertEqual(
h_dataframe.iloc[0].get('dimension'), 'Point Temperature'
)
self.assertEqual(
h_dataframe.iloc[0].get('event'), 'Communication State'
)
self.assertEqual(h_dataframe.iloc[0].get('dimension_unity'), '°C')
self.assertEqual(
h_dataframe.iloc[1].get('dimension_thing'), 'Sensor_Inobram_TU'
)
self.assertEqual(
h_dataframe.iloc[1].get('dimension'), 'Point Humidity'
)
self.assertEqual(
h_dataframe.iloc[1].get('event'), 'Communication State'
)
self.assertEqual(h_dataframe.iloc[1].get('dimension_unity'), '%')
def test_humanize_json(self):
json_ = {
'device': 'AAAABBBBCCCC',
'channel_id': 'AAAABBBBCCCC',
'channel_code': 14,
'thing_code': 14,
'ports': [{
'port': "0",
'thing_code': 14,
'sensors': [{
'sensor': '1',
'last_package': {
'header_timestamp': '2021-02-04T14:09:38.115Z',
'dimension_value': 1847,
'dimension_code': '15',
'dimension_unity_code': 6,
'dimension_thing_code': 14
}
}]
}]
}
h_json = utils.humanize_json(json_)
self.assertDictEqual(h_json, {
'device': 'AAAABBBBCCCC',
'channel_id': 'AAAABBBBCCCC',
'channel_code': 14,
'channel': 'T4_Agriness_v1',
'thing_code': 14,
'thing': 'T4_Agriness_v1',
'ports': [{
'port': "0",
'thing_code': 14,
'thing': 'T4_Agriness_v1',
'sensors': [{
'sensor': '1',
'last_package': {
'header_timestamp': '2021-02-04T14:09:38.115Z',
'dimension_value': 1847,
'dimension_code': '15',
'dimension': 'Accumulated Time',
'dimension_unity_code': 6,
'dimension_unity': 's',
'dimension_thing_code': 14,
'dimension_thing': 'T4_Agriness_v1'
}
}]
}]
})
|
class TestHumanization(unittest.TestCase):
'''Set of unit tests for all functions concerning humanization of data.
'''
def test_humanize_thing_code(self):
pass
def test_humanize_dimension_code(self):
pass
def test_humanize_event_code(self):
pass
def test_humanize_unity_code(self):
pass
def test_humanize_dataframe(self):
pass
def test_humanize_json(self):
pass
| 7 | 1 | 23 | 2 | 21 | 0 | 1 | 0.02 | 1 | 0 | 0 | 0 | 6 | 0 | 6 | 78 | 144 | 16 | 126 | 15 | 119 | 2 | 50 | 15 | 43 | 1 | 2 | 0 | 6 |
3,223 |
AgrinessEdgeIoT/portiapy
|
AgrinessEdgeIoT_portiapy/portiapy/profile.py
|
portiapy.profile.ProfileStrategies
|
class ProfileStrategies(Enum):
BY_ZERO_PORT = 1
BY_PORTS = 2
@property
def endpoint(self):
return self.name.lower().replace('_', '')
|
class ProfileStrategies(Enum):
@property
def endpoint(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 50 | 7 | 1 | 6 | 5 | 3 | 0 | 5 | 4 | 3 | 1 | 4 | 0 | 1 |
3,224 |
AgrinessEdgeIoT/portiapy
|
AgrinessEdgeIoT_portiapy/portiapy/summary.py
|
portiapy.summary.SummaryStrategies
|
class SummaryStrategies(Enum):
PER_MINUTE = 1
PER_HOUR = 2
PER_DAY = 3
PER_MONTH = 4
PER_YEAR = 5
@property
def endpoint(self):
return self.name.lower().replace('_', '')
|
class SummaryStrategies(Enum):
@property
def endpoint(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 50 | 10 | 1 | 9 | 8 | 6 | 0 | 8 | 7 | 6 | 1 | 4 | 0 | 1 |
3,225 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/tests/integration/test_portia.py
|
tests.integration.test_portia.TestEdgeDeviceDimensionFromPort
|
class TestEdgeDeviceDimensionFromPort(unittest.TestCase):
"""Set of integration tests for all functions concerning the
EdgeDeviceDimensionFromPort instance.
"""
@classmethod
def setUpClass(cls):
"""Creates a Portia configuration to test the instance.
"""
# Settings for test
base_url = os.getenv('PORTIA_URL', 'https://api-portia.agriness.io/v3')
token = os.getenv('PORTIA_TOKEN')
# Creating Portia API instance
cls.portia_api = portia.PortiaApi({
'baseurl': base_url,
'authorization': token,
'debug': False,
'Accept': 'text/csv'
})
def test_select(self):
dimensions = self.portia_api.device('2DPEQ572HEXP').port(4) \
.dimension(1).select(params={
'from': 1609470000000,
'to': 1609729199000,
'lower_bound': None,
'upper_bound': None,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
})
for i, row in dimensions.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
for i, row in dimensions.humanize().iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_thing, 'Sensor_Inobram_TU')
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_unity, '°C')
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.dimension, 'Point Temperature')
def test_select_last(self):
dimensions = self.portia_api.device('2DPEQ572HEXP').port(4) \
.dimension(1).select(
last=True,
params={
'from': 1609470000000,
'to': 1609729199000,
'lower_bound': None,
'upper_bound': None,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
self.assertEqual(dimensions.iloc[0].dimension_thing_code, 16)
self.assertEqual(dimensions.iloc[0].dimension_unity_code, 1)
self.assertEqual(dimensions.iloc[0].dimension_code, 1)
humanized_dimensions = dimensions.humanize()
self.assertEqual(
humanized_dimensions.iloc[0].dimension_thing_code, 16
)
self.assertEqual(
humanized_dimensions.iloc[0].dimension_thing, 'Sensor_Inobram_TU'
)
self.assertEqual(
humanized_dimensions.iloc[0].dimension_unity_code, 1
)
self.assertEqual(
humanized_dimensions.iloc[0].dimension_unity, '°C'
)
self.assertEqual(
humanized_dimensions.iloc[0].dimension_code, 1
)
self.assertEqual(
humanized_dimensions.iloc[0].dimension, 'Point Temperature'
)
def test_events(self):
events = self.portia_api.device('2DPEQ572HEXP').port(4) \
.dimension(1).events(params={
'from': 1609470000000,
'to': 1609729199000,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
})
for i, row in events.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.event_code, 1)
for i, row in events.humanize().iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_thing, 'Sensor_Inobram_TU')
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_unity, '°C')
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.dimension, 'Point Temperature')
self.assertEqual(row.event_code, 1)
self.assertEqual(row.event, 'Communication State')
def test_events_last(self):
events = self.portia_api.device('2DPEQ572HEXP').port(4) \
.dimension(1).events(
last=True,
params={
'from': 1609470000000,
'to': 1609729199000,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
self.assertEqual(events.iloc[0].dimension_thing_code, 16)
self.assertEqual(events.iloc[0].dimension_unity_code, 1)
self.assertEqual(events.iloc[0].dimension_code, 1)
self.assertEqual(events.iloc[0].event_code, 1)
humanized_events = events.humanize()
self.assertEqual(
humanized_events.iloc[0].dimension_thing_code, 16
)
self.assertEqual(
humanized_events.iloc[0].dimension_thing, 'Sensor_Inobram_TU'
)
self.assertEqual(
humanized_events.iloc[0].dimension_unity_code, 1
)
self.assertEqual(
humanized_events.iloc[0].dimension_unity, '°C'
)
self.assertEqual(
humanized_events.iloc[0].dimension_code, 1
)
self.assertEqual(
humanized_events.iloc[0].dimension, 'Point Temperature'
)
self.assertEqual(
humanized_events.iloc[0].event_code, 1
)
self.assertEqual(
humanized_events.iloc[0].event, 'Communication State'
)
|
class TestEdgeDeviceDimensionFromPort(unittest.TestCase):
'''Set of integration tests for all functions concerning the
EdgeDeviceDimensionFromPort instance.
'''
@classmethod
def setUpClass(cls):
'''Creates a Portia configuration to test the instance.
'''
pass
def test_select(self):
pass
def test_select_last(self):
pass
def test_events(self):
pass
def test_events_last(self):
pass
| 7 | 2 | 30 | 2 | 27 | 1 | 2 | 0.05 | 1 | 1 | 1 | 0 | 4 | 0 | 5 | 77 | 158 | 14 | 137 | 17 | 130 | 7 | 61 | 16 | 55 | 3 | 2 | 1 | 9 |
3,226 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/portiapy/portia.py
|
portiapy.portia.EdgeDeviceEventFromSensorDimension
|
class EdgeDeviceEventFromSensorDimension(object):
"""Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID, a port, sensor, dimension code and an event code.
"""
def __init__(
self,
edge_device_dimension_from_sensor: EdgeDeviceDimensionFromSensor,
event: int,
portia_config: dict
):
"""EdgeDeviceEventFromDimension's constructor.
Arguments:
edge_device_dimension_from_sensor {EdgeDeviceDimensionFromSensor}
-- instance of an Edge device dimension from sensor
event {int} -- event code of the device
portia_config {dict} -- Portia's configuration arguments
"""
self.edge_id = edge_device_dimension_from_sensor.edge_id
self.port = edge_device_dimension_from_sensor.port
self.sensor = edge_device_dimension_from_sensor.sensor
self.dimension = edge_device_dimension_from_sensor.dimension
self.event = event
self.portia_config = portia_config
def events(self, last: bool = False, params: dict = None) -> object:
"""Retrieves a device's events by its port, sensor, dimension code and
event code.
Keyword Arguments:
last {bool} -- if the last event should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's events
"""
return add_humanize_method(events.query_by_port_sensor_dimension_event(
self.portia_config,
self.edge_id,
self.port,
self.sensor,
self.dimension,
self.event,
last,
params
))
|
class EdgeDeviceEventFromSensorDimension(object):
'''Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID, a port, sensor, dimension code and an event code.
'''
def __init__(
self,
edge_device_dimension_from_sensor: EdgeDeviceDimensionFromSensor,
event: int,
portia_config: dict
):
'''EdgeDeviceEventFromDimension's constructor.
Arguments:
edge_device_dimension_from_sensor {EdgeDeviceDimensionFromSensor}
-- instance of an Edge device dimension from sensor
event {int} -- event code of the device
portia_config {dict} -- Portia's configuration arguments
'''
pass
def events(self, last: bool = False, params: dict = None) -> object:
'''Retrieves a device's events by its port, sensor, dimension code and
event code.
Keyword Arguments:
last {bool} -- if the last event should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's events
'''
pass
| 3 | 3 | 21 | 2 | 12 | 8 | 1 | 0.79 | 1 | 4 | 1 | 0 | 2 | 6 | 2 | 2 | 47 | 4 | 24 | 14 | 16 | 19 | 10 | 9 | 7 | 1 | 1 | 0 | 2 |
3,227 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/tests/integration/test_profile.py
|
tests.integration.test_profile.TestProfile
|
class TestProfile(unittest.TestCase):
"""Set of integration tests for all functions concerning the profile
module.
"""
@classmethod
def setUpClass(cls):
"""Creates a Portia configuration to test the adapter.
"""
# Settings for test
base_url = os.getenv(
'PORTIA_URL', 'https://api-portia.agriness.com/v3'
)
token = os.getenv('PORTIA_TOKEN')
# Creating portia configuration
cls.portia_config = {
'baseurl': base_url,
'authorization': token,
'debug': False,
'Accept': 'text/csv'
}
def test_profile_strategies(self):
by_zero_port = profile.ProfileStrategies.BY_ZERO_PORT
by_ports = profile.ProfileStrategies.BY_PORTS
self.assertEqual(by_zero_port.endpoint, 'byzeroport')
self.assertEqual(by_ports.endpoint, 'byports')
def test_device_profile(self):
device = profile.device_profile(self.portia_config, '2DPEQ572HEXP')
self.assertEqual(device.get('device'), '2DPEQ572HEXP')
self.assertEqual(device.get('channel_id'), '1BTU7542G5EY')
self.assertEqual(device.get('channel_code'), 14)
self.assertEqual(device.get('thing_code'), 69)
self.assertEqual(len(device.get('ports')), 9)
def test_port_profile(self):
port = profile.port_profile(self.portia_config, '2DPEQ572HEXP', 4)
self.assertEqual(port.get('device'), '2DPEQ572HEXP')
self.assertEqual(port.get('channel_id'), '1BTU7542G5EY')
self.assertEqual(port.get('channel_code'), 14)
self.assertEqual(port.get('thing_code'), 69)
self.assertEqual(len(port.get('ports')), 1)
self.assertEqual(len(port.get('ports')[0].get('sensors')), 2)
def test_sensor_profile(self):
sensor = profile.sensor_profile(
self.portia_config, '2DPEQ572HEXP', 4, 1
)
self.assertEqual(sensor.get('device'), '2DPEQ572HEXP')
self.assertEqual(sensor.get('channel_id'), '1BTU7542G5EY')
self.assertEqual(sensor.get('channel_code'), 14)
self.assertEqual(sensor.get('thing_code'), 69)
self.assertEqual(len(sensor.get('ports')), 1)
self.assertEqual(len(sensor.get('ports')[0].get('sensors')), 1)
|
class TestProfile(unittest.TestCase):
'''Set of integration tests for all functions concerning the profile
module.
'''
@classmethod
def setUpClass(cls):
'''Creates a Portia configuration to test the adapter.
'''
pass
def test_profile_strategies(self):
pass
def test_device_profile(self):
pass
def test_port_profile(self):
pass
def test_sensor_profile(self):
pass
| 7 | 2 | 10 | 1 | 8 | 1 | 1 | 0.16 | 1 | 1 | 1 | 0 | 4 | 0 | 5 | 77 | 60 | 10 | 43 | 14 | 36 | 7 | 33 | 13 | 27 | 1 | 2 | 0 | 5 |
3,228 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/portiapy/portia.py
|
portiapy.portia.EdgeDeviceEventFromDimension
|
class EdgeDeviceEventFromDimension(object):
"""Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID, a port a dimension code and an event code.
"""
def __init__(
self,
edge_device_dimension_from_port: EdgeDeviceDimensionFromPort,
event: int,
portia_config: dict
):
"""EdgeDeviceEventFromDimension's constructor.
Arguments:
edge_device_dimension_from_port {EdgeDeviceDimensionFromPort} --
instance of an Edge device dimension from port
event {int} -- event code of the device
portia_config {dict} -- Portia's configuration arguments
"""
self.edge_id = edge_device_dimension_from_port.edge_id
self.port = edge_device_dimension_from_port.port
self.dimension = edge_device_dimension_from_port.dimension
self.event = event
self.portia_config = portia_config
def events(self, last: bool = False, params: dict = None) -> object:
"""Retrieves a device's events by its port, dimension code and event
code.
Keyword Arguments:
last {bool} -- if the last event should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's events
"""
return add_humanize_method(events.query_by_port_dimension_event(
self.portia_config,
self.edge_id,
self.port,
self.dimension,
self.event,
last,
params
))
|
class EdgeDeviceEventFromDimension(object):
'''Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID, a port a dimension code and an event code.
'''
def __init__(
self,
edge_device_dimension_from_port: EdgeDeviceDimensionFromPort,
event: int,
portia_config: dict
):
'''EdgeDeviceEventFromDimension's constructor.
Arguments:
edge_device_dimension_from_port {EdgeDeviceDimensionFromPort} --
instance of an Edge device dimension from port
event {int} -- event code of the device
portia_config {dict} -- Portia's configuration arguments
'''
pass
def events(self, last: bool = False, params: dict = None) -> object:
'''Retrieves a device's events by its port, dimension code and event
code.
Keyword Arguments:
last {bool} -- if the last event should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's events
'''
pass
| 3 | 3 | 20 | 2 | 11 | 8 | 1 | 0.86 | 1 | 4 | 1 | 0 | 2 | 5 | 2 | 2 | 45 | 4 | 22 | 13 | 14 | 19 | 9 | 8 | 6 | 1 | 1 | 0 | 2 |
3,229 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/portiapy/portia.py
|
portiapy.portia.EdgeDeviceEventFromSensor
|
class EdgeDeviceEventFromSensor(object):
"""Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID, a port a sensor and an event code.
"""
def __init__(
self,
edge_device_sensor: EdgeDeviceSensor,
event: int,
portia_config: dict
):
"""EdgeDeviceEventFromSensor's constructor.
Arguments:
edge_device_sensor {EdgeDeviceSensor} -- instance of an Edge device
sensor
event {int} -- event code of the device
portia_config {dict} -- Portia's configuration arguments
"""
self.edge_id = edge_device_sensor.edge_id
self.port = edge_device_sensor.port
self.sensor = edge_device_sensor.sensor
self.event = event
self.portia_config = portia_config
def events(self, last: bool = False, params: dict = None) -> object:
"""Retrieves a device's events by its port, sensor and event code.
Keyword Arguments:
last {bool} -- if the last event should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's events
"""
return add_humanize_method(events.query_by_port_sensor_event(
self.portia_config,
self.edge_id,
self.port,
self.sensor,
self.event,
last,
params
))
|
class EdgeDeviceEventFromSensor(object):
'''Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID, a port a sensor and an event code.
'''
def __init__(
self,
edge_device_sensor: EdgeDeviceSensor,
event: int,
portia_config: dict
):
'''EdgeDeviceEventFromSensor's constructor.
Arguments:
edge_device_sensor {EdgeDeviceSensor} -- instance of an Edge device
sensor
event {int} -- event code of the device
portia_config {dict} -- Portia's configuration arguments
'''
pass
def events(self, last: bool = False, params: dict = None) -> object:
'''Retrieves a device's events by its port, sensor and event code.
Keyword Arguments:
last {bool} -- if the last event should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's events
'''
pass
| 3 | 3 | 20 | 2 | 11 | 8 | 1 | 0.82 | 1 | 4 | 1 | 0 | 2 | 5 | 2 | 2 | 44 | 4 | 22 | 13 | 14 | 18 | 9 | 8 | 6 | 1 | 1 | 0 | 2 |
3,230 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/portiapy/portia.py
|
portiapy.portia.CustomDict
|
class CustomDict(dict):
"""Custom dictionary with an humanization method.
Extends:
dict
"""
def humanize(
self,
locale='en-us',
custom_dimension: dict = None,
custom_event: dict = None,
custom_unity: dict = None
) -> dict:
"""Humanizes dictionary.
Keyword Arguments:
locale {str} -- which language to use when humanizing
(default {'en-us'})
custom_dimension {dict} -- custom list of dimension codes
(default {None})
custom_event {dict} -- custom list of event codes (default {None})
custom_unity {dict} -- custom list of unity codes (default {None})
Returns:
dict -- humanized dictionary
"""
return utils.humanize_json(
self, locale, custom_dimension, custom_unity
)
|
class CustomDict(dict):
'''Custom dictionary with an humanization method.
Extends:
dict
'''
def humanize(
self,
locale='en-us',
custom_dimension: dict = None,
custom_event: dict = None,
custom_unity: dict = None
) -> dict:
'''Humanizes dictionary.
Keyword Arguments:
locale {str} -- which language to use when humanizing
(default {'en-us'})
custom_dimension {dict} -- custom list of dimension codes
(default {None})
custom_event {dict} -- custom list of event codes (default {None})
custom_unity {dict} -- custom list of unity codes (default {None})
Returns:
dict -- humanized dictionary
'''
pass
| 2 | 2 | 23 | 2 | 10 | 11 | 1 | 1.36 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 28 | 29 | 3 | 11 | 8 | 3 | 15 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
3,231 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/portiapy/portia.py
|
portiapy.portia.EdgeDevice
|
class EdgeDevice(object):
"""Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID.
"""
def __init__(self, edge_id: str, portia_config: dict):
"""EdgeDevice's constructor.
Arguments:
edge_id {str} -- Edge ID that identifies the device
portia_config {dict} -- Portia's configuration arguments
"""
self.edge_id = edge_id
self.portia_config = portia_config
def port(self, port: int) -> 'EdgeDevicePort':
"""Builds a new EdgeDevicePort instance.
Arguments:
port {int} -- port of the device
Returns:
EdgeDevicePort -- EdgeDevicePort instance
"""
return EdgeDevicePort(self, port, self.portia_config)
def dimension(self, dimension: int) -> 'EdgeDeviceDimensionFromDevice':
"""Builds a new EdgeDeviceDimensionFromDevice instance.
Arguments:
dimension {int} -- dimension of the device
Returns:
EdgeDeviceDimensionFromDevice -- EdgeDeviceDimensionFromDevice
instance
"""
return EdgeDeviceDimensionFromDevice(
self, dimension, self.portia_config
)
def ports(self, last: bool = False, params: dict = None) -> object:
"""Lists a device's ports.
Keyword Arguments:
last {bool} -- if the last package of each port should be returned
or not (default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the list of ports
"""
return add_humanize_method(describe.device_ports(
self.portia_config, self.edge_id, last, params
))
def profile(
self,
strategy: 'ProfileStrategies' = profile.ProfileStrategies.BY_ZERO_PORT,
interval: int = 30,
params: dict = None
) -> dict:
"""Retrieves a device's profile.
Keyword Arguments:
strategy {ProfileStrategies} -- strategy to use when building the
profile (default:
{ProfileStrategies.BY_ZERO_PORT})
interval {int} -- interval of time in minutes to build the profile
(default: {30})
params {dict} -- params to send to the service (default: {None})
Returns:
dict -- dictionary with the device's profile
"""
return add_humanize_method(profile.device_profile(
self.portia_config, self.edge_id, strategy, interval, params
))
|
class EdgeDevice(object):
'''Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID.
'''
def __init__(self, edge_id: str, portia_config: dict):
'''EdgeDevice's constructor.
Arguments:
edge_id {str} -- Edge ID that identifies the device
portia_config {dict} -- Portia's configuration arguments
'''
pass
def port(self, port: int) -> 'EdgeDevicePort':
'''Builds a new EdgeDevicePort instance.
Arguments:
port {int} -- port of the device
Returns:
EdgeDevicePort -- EdgeDevicePort instance
'''
pass
def dimension(self, dimension: int) -> 'EdgeDeviceDimensionFromDevice':
'''Builds a new EdgeDeviceDimensionFromDevice instance.
Arguments:
dimension {int} -- dimension of the device
Returns:
EdgeDeviceDimensionFromDevice -- EdgeDeviceDimensionFromDevice
instance
'''
pass
def ports(self, last: bool = False, params: dict = None) -> object:
'''Lists a device's ports.
Keyword Arguments:
last {bool} -- if the last package of each port should be returned
or not (default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the list of ports
'''
pass
def profile(
self,
strategy: 'ProfileStrategies' = profile.ProfileStrategies.BY_ZERO_PORT,
interval: int = 30,
params: dict = None
) -> dict:
'''Retrieves a device's profile.
Keyword Arguments:
strategy {ProfileStrategies} -- strategy to use when building the
profile (default:
{ProfileStrategies.BY_ZERO_PORT})
interval {int} -- interval of time in minutes to build the profile
(default: {30})
params {dict} -- params to send to the service (default: {None})
Returns:
dict -- dictionary with the device's profile
'''
pass
| 6 | 6 | 14 | 2 | 4 | 7 | 1 | 1.74 | 1 | 6 | 2 | 0 | 5 | 2 | 5 | 5 | 76 | 13 | 23 | 13 | 12 | 40 | 12 | 8 | 6 | 1 | 1 | 0 | 5 |
3,232 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/portiapy/portia.py
|
portiapy.portia.EdgeDeviceDimensionFromDevice
|
class EdgeDeviceDimensionFromDevice(object):
"""Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID and a dimension code.
"""
def __init__(
self,
edge_device: EdgeDevice,
dimension: int,
portia_config: dict
):
"""EdgeDeviceDimensionFromDevice's constructor.
Arguments:
edge_device {EdgeDevice} -- instance of an Edge device
dimension {int} -- dimension code of the device
portia_config {dict} -- Portia's configuration arguments
"""
self.edge_id = edge_device.edge_id
self.dimension = dimension
self.portia_config = portia_config
def summary(
self,
series: list = None,
strategy: 'SummaryStrategies' = summary.SummaryStrategies.PER_HOUR,
interval=1,
params=None
) -> object:
"""Summarizes a device by dimension code.
Keyword Arguments:
series {list} -- list of series to summarize (default: {None})
strategy {SummaryStrategies} -- strategy to use when summarizing
(default:
{SummaryStrategies.PER_HOUR})
interval {int} -- interval of time to summarize (default: {1})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's summarized dimensions
"""
return add_humanize_method(summary.query_device_by_dimension(
self.portia_config,
self.edge_id,
self.dimension,
series,
strategy,
interval,
params
))
|
class EdgeDeviceDimensionFromDevice(object):
'''Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID and a dimension code.
'''
def __init__(
self,
edge_device: EdgeDevice,
dimension: int,
portia_config: dict
):
'''EdgeDeviceDimensionFromDevice's constructor.
Arguments:
edge_device {EdgeDevice} -- instance of an Edge device
dimension {int} -- dimension code of the device
portia_config {dict} -- Portia's configuration arguments
'''
pass
def summary(
self,
series: list = None,
strategy: 'SummaryStrategies' = summary.SummaryStrategies.PER_HOUR,
interval=1,
params=None
) -> object:
'''Summarizes a device by dimension code.
Keyword Arguments:
series {list} -- list of series to summarize (default: {None})
strategy {SummaryStrategies} -- strategy to use when summarizing
(default:
{SummaryStrategies.PER_HOUR})
interval {int} -- interval of time to summarize (default: {1})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's summarized dimensions
'''
pass
| 3 | 3 | 23 | 2 | 13 | 9 | 1 | 0.77 | 1 | 4 | 1 | 0 | 2 | 3 | 2 | 2 | 50 | 4 | 26 | 17 | 12 | 20 | 7 | 6 | 4 | 1 | 1 | 0 | 2 |
3,233 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/tests/integration/test_portia.py
|
tests.integration.test_portia.TestEdgeDeviceEventFromSensorDimension
|
class TestEdgeDeviceEventFromSensorDimension(unittest.TestCase):
"""Set of integration tests for all functions concerning the
EdgeDeviceEventFromSensorDimension instance.
"""
@classmethod
def setUpClass(cls):
"""Creates a Portia configuration to test the instance.
"""
# Settings for test
base_url = os.getenv('PORTIA_URL', 'https://api-portia.agriness.io/v3')
token = os.getenv('PORTIA_TOKEN')
# Creating Portia API instance
cls.portia_api = portia.PortiaApi({
'baseurl': base_url,
'authorization': token,
'debug': False,
'Accept': 'text/csv'
})
def test_events(self):
events = self.portia_api.device('2DPEQ572HEXP').port(4).sensor(1) \
.dimension(1).event(1).events(params={
'from': 1609470000000,
'to': 1609729199000,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
})
for i, row in events.iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.event_code, 1)
for i, row in events.humanize().iterrows():
self.assertEqual(row.dimension_thing_code, 16)
self.assertEqual(row.dimension_thing, 'Sensor_Inobram_TU')
self.assertEqual(row.dimension_unity_code, 1)
self.assertEqual(row.dimension_unity, '°C')
self.assertEqual(row.dimension_code, 1)
self.assertEqual(row.dimension, 'Point Temperature')
self.assertEqual(row.event_code, 1)
self.assertEqual(row.event, 'Communication State')
def test_events_last(self):
events = self.portia_api.device('2DPEQ572HEXP').port(4).sensor(1) \
.dimension(1).event(1).events(
last=True,
params={
'from': 1609470000000,
'to': 1609729199000,
'order': None,
'limit': None,
'precision': 'ms',
'timezone': 'Etc/UTC'
}
)
self.assertEqual(events.iloc[0].dimension_thing_code, 16)
self.assertEqual(events.iloc[0].dimension_unity_code, 1)
self.assertEqual(events.iloc[0].dimension_code, 1)
self.assertEqual(events.iloc[0].event_code, 1)
humanized_events = events.humanize()
self.assertEqual(
humanized_events.iloc[0].dimension_thing_code, 16
)
self.assertEqual(
humanized_events.iloc[0].dimension_thing, 'Sensor_Inobram_TU'
)
self.assertEqual(
humanized_events.iloc[0].dimension_unity_code, 1
)
self.assertEqual(
humanized_events.iloc[0].dimension_unity, '°C'
)
self.assertEqual(
humanized_events.iloc[0].dimension_code, 1
)
self.assertEqual(
humanized_events.iloc[0].dimension, 'Point Temperature'
)
self.assertEqual(
humanized_events.iloc[0].event_code, 1
)
self.assertEqual(
humanized_events.iloc[0].event, 'Communication State'
)
|
class TestEdgeDeviceEventFromSensorDimension(unittest.TestCase):
'''Set of integration tests for all functions concerning the
EdgeDeviceEventFromSensorDimension instance.
'''
@classmethod
def setUpClass(cls):
'''Creates a Portia configuration to test the instance.
'''
pass
def test_events(self):
pass
def test_events_last(self):
pass
| 5 | 2 | 28 | 2 | 25 | 1 | 2 | 0.09 | 1 | 1 | 1 | 0 | 2 | 0 | 3 | 75 | 92 | 8 | 77 | 11 | 72 | 7 | 36 | 10 | 32 | 3 | 2 | 1 | 5 |
3,234 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/portiapy/portia.py
|
portiapy.portia.EdgeDeviceDimensionFromSensor
|
class EdgeDeviceDimensionFromSensor(object):
"""Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID, a port, a sensor and a dimension code.
"""
def __init__(
self,
edge_device_sensor: EdgeDeviceSensor,
dimension: int,
portia_config: dict
):
"""EdgeDeviceDimensionFromSensor's constructor.
Arguments:
edge_device_sensor {EdgeDeviceSensor} -- instance of an Edge device
sensor
dimension {int} -- dimension code of the device
portia_config {dict} -- Portia's configuration arguments
"""
self.edge_id = edge_device_sensor.edge_id
self.port = edge_device_sensor.port
self.sensor = edge_device_sensor.sensor
self.dimension = dimension
self.portia_config = portia_config
def event(self, event: int) -> 'EdgeDeviceEventFromSensorDimension':
"""Builds a new EdgeDeviceEventFromSensorDimension instance.
Arguments:
event {int} -- event code of the device
Returns:
EdgeDeviceEventFromSensorDimension --
EdgeDeviceEventFromSensorDimension instance
"""
return EdgeDeviceEventFromSensorDimension(
self, event, self.portia_config
)
def select(self, last: bool = False, params: dict = None) -> object:
"""Retrieves a device's series by its port, sensor and dimension code.
Keyword Arguments:
last {bool} -- if the last package should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's dimensions
"""
return add_humanize_method(select.query_by_port_sensor_dimension(
self.portia_config,
self.edge_id,
self.port,
self.sensor,
self.dimension,
last,
params
))
def summary(
self,
strategy: 'SummaryStrategies' = summary.SummaryStrategies.PER_HOUR,
interval=1,
params=None
) -> object:
"""Summarizes a device by port, sensor and dimension code.
Keyword Arguments:
strategy {SummaryStrategies} -- strategy to use when summarizing
(default:
{SummaryStrategies.PER_HOUR})
interval {int} -- interval of time to summarize (default: {1})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's summarized dimensions
"""
return add_humanize_method(summary.query_by_port_sensor_dimension(
self.portia_config,
self.edge_id,
self.port,
self.sensor,
self.dimension,
strategy,
interval,
params
))
def events(self, last: bool = False, params: dict = None) -> object:
"""Retrieves a device's events by its port, sensor and dimension code.
Keyword Arguments:
last {bool} -- if the last event should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's events
"""
return add_humanize_method(events.query_by_port_sensor_dimension(
self.portia_config,
self.edge_id,
self.port,
self.sensor,
self.dimension,
last,
params
))
|
class EdgeDeviceDimensionFromSensor(object):
'''Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID, a port, a sensor and a dimension code.
'''
def __init__(
self,
edge_device_sensor: EdgeDeviceSensor,
dimension: int,
portia_config: dict
):
'''EdgeDeviceDimensionFromSensor's constructor.
Arguments:
edge_device_sensor {EdgeDeviceSensor} -- instance of an Edge device
sensor
dimension {int} -- dimension code of the device
portia_config {dict} -- Portia's configuration arguments
'''
pass
def event(self, event: int) -> 'EdgeDeviceEventFromSensorDimension':
'''Builds a new EdgeDeviceEventFromSensorDimension instance.
Arguments:
event {int} -- event code of the device
Returns:
EdgeDeviceEventFromSensorDimension --
EdgeDeviceEventFromSensorDimension instance
'''
pass
def select(self, last: bool = False, params: dict = None) -> object:
'''Retrieves a device's series by its port, sensor and dimension code.
Keyword Arguments:
last {bool} -- if the last package should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's dimensions
'''
pass
def summary(
self,
strategy: 'SummaryStrategies' = summary.SummaryStrategies.PER_HOUR,
interval=1,
params=None
) -> object:
'''Summarizes a device by port, sensor and dimension code.
Keyword Arguments:
strategy {SummaryStrategies} -- strategy to use when summarizing
(default:
{SummaryStrategies.PER_HOUR})
interval {int} -- interval of time to summarize (default: {1})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's summarized dimensions
'''
pass
def events(self, last: bool = False, params: dict = None) -> object:
'''Retrieves a device's events by its port, sensor and dimension code.
Keyword Arguments:
last {bool} -- if the last event should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's events
'''
pass
| 6 | 6 | 20 | 2 | 10 | 8 | 1 | 0.83 | 1 | 5 | 2 | 0 | 5 | 5 | 5 | 5 | 108 | 13 | 52 | 21 | 36 | 43 | 15 | 11 | 9 | 1 | 1 | 0 | 5 |
3,235 |
AgrinessEdgeIoT/portiapy
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AgrinessEdgeIoT_portiapy/portiapy/portia.py
|
portiapy.portia.EdgeDeviceDimensionFromPort
|
class EdgeDeviceDimensionFromPort(object):
"""Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID, a port and a dimension code.
"""
def __init__(
self,
edge_device_port: EdgeDevicePort,
dimension: int,
portia_config: dict
):
"""EdgeDeviceDimensionFromPort's constructor.
Arguments:
edge_device_port {EdgeDevicePort} -- instance of an Edge device
port
dimension {int} -- dimension code of the device
portia_config {dict} -- Portia's configuration arguments
"""
self.edge_id = edge_device_port.edge_id
self.port = edge_device_port.port
self.dimension = dimension
self.portia_config = portia_config
def event(self, event: int) -> 'EdgeDeviceEventFromDimension':
"""Builds a new EdgeDeviceEventFromDimension instance.
Arguments:
event {int} -- event code of the device
Returns:
EdgeDeviceEventFromDimension -- EdgeDeviceEventFromDimension
instance
"""
return EdgeDeviceEventFromDimension(self, event, self.portia_config)
def select(self, last: bool = False, params: dict = None) -> object:
"""Retrieves a device's series by its port and dimension code.
Keyword Arguments:
last {bool} -- if the last package should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's dimensions
"""
return add_humanize_method(select.query_by_port_dimension(
self.portia_config,
self.edge_id,
self.port,
self.dimension,
last,
params
))
def events(self, last: bool = False, params: dict = None) -> object:
"""Retrieves a device's events by its port and dimension code.
Keyword Arguments:
last {bool} -- if the last event should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's events
"""
return add_humanize_method(events.query_by_port_dimension(
self.portia_config,
self.edge_id,
self.port,
self.dimension,
last,
params
))
|
class EdgeDeviceDimensionFromPort(object):
'''Abstracts usage of all Portia endpoints concerning data that only need
an Edge ID, a port and a dimension code.
'''
def __init__(
self,
edge_device_port: EdgeDevicePort,
dimension: int,
portia_config: dict
):
'''EdgeDeviceDimensionFromPort's constructor.
Arguments:
edge_device_port {EdgeDevicePort} -- instance of an Edge device
port
dimension {int} -- dimension code of the device
portia_config {dict} -- Portia's configuration arguments
'''
pass
def event(self, event: int) -> 'EdgeDeviceEventFromDimension':
'''Builds a new EdgeDeviceEventFromDimension instance.
Arguments:
event {int} -- event code of the device
Returns:
EdgeDeviceEventFromDimension -- EdgeDeviceEventFromDimension
instance
'''
pass
def select(self, last: bool = False, params: dict = None) -> object:
'''Retrieves a device's series by its port and dimension code.
Keyword Arguments:
last {bool} -- if the last package should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's dimensions
'''
pass
def events(self, last: bool = False, params: dict = None) -> object:
'''Retrieves a device's events by its port and dimension code.
Keyword Arguments:
last {bool} -- if the last event should be returned or not
(default: {False})
params {dict} -- params to send to the service (default: {None})
Returns:
object -- object with the device's events
'''
pass
| 5 | 5 | 17 | 2 | 8 | 8 | 1 | 1.06 | 1 | 5 | 2 | 0 | 4 | 4 | 4 | 4 | 74 | 10 | 31 | 14 | 21 | 33 | 12 | 9 | 7 | 1 | 1 | 0 | 4 |
3,236 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_onshape_parser.py
|
test_onshape_parser.OnshapeParserTest
|
class OnshapeParserTest(unittest.TestCase):
def test_parse_quanity(self):
d0 = {'value': 0.1414213562373095,
'unitToPower': [{'value': 1, 'key': 'METER'}], 'typeTag': ''}
d1 = {'value': 0.1414213562373095,
'unitToPower': [{'value': 3, 'key': 'MILLIMETER'}], 'typeTag': ''}
d2 = {'value': 0.001414213562373095,
'unitToPower': [{'value': 1, 'key': 'METER'}], 'typeTag': ''}
d3 = {'value': 1414.213562373095,
'unitToPower': [{'value': 1, 'key': 'METER'}], 'typeTag': ''}
d4 = {'value': 1414213.562373095,
'unitToPower': [{'value': 2, 'key': 'METER'}], 'typeTag': ''}
d5 = {'value': 0.00043,
'unitToPower': [{'value': 2, 'key': 'METER'}], 'typeTag': ''}
d6 = {'value': 0.00000043,
'unitToPower': [{'value': 2, 'key': 'METER'}], 'typeTag': ''}
d7 = {'value': 1414213562.373095,
'unitToPower': [{'value': 3, 'key': 'METER'}], 'typeTag': ''}
d8 = {'value': 0.00000043,
'unitToPower': [{'value': 3, 'key': 'METER'}], 'typeTag': ''}
d9 = {'value': 0.0043,
'unitToPower': [{'value': 3, 'key': 'METER'}], 'typeTag': ''}
d10 = {'value': 0.1414213562373095,
'unitToPower': [{'value': -1, 'key': 'METER'}], 'typeTag': ''}
d11 = {'value': -0.0043,
'unitToPower': [{'value': 1, 'key': 'METER'}], 'typeTag': ''}
self.assertEqual(parse.parse_quantity(d0), '14.14 cm')
self.assertEqual(parse.parse_quantity(d0, False),
0.1414213562373095 * u.m)
self.assertEqual(parse.parse_quantity(d1), '0.14 mm ** 3')
self.assertEqual(parse.parse_quantity(d2), '1.41 mm')
self.assertEqual(parse.parse_quantity(d3), '1.41 km')
self.assertEqual(parse.parse_quantity(d4), '1.41 km ** 2')
self.assertEqual(parse.parse_quantity(d5), '4.3 cm ** 2')
self.assertEqual(parse.parse_quantity(d6), '0.43 mm ** 2')
self.assertEqual(parse.parse_quantity(d7), '1414213562.37 kl')
self.assertEqual(parse.parse_quantity(d8), '0.43 ml')
self.assertEqual(parse.parse_quantity(d9), '4.3 l')
self.assertEqual(parse.parse_quantity(d10), '0.14 / m')
self.assertEqual(parse.parse_quantity(d11), '-0.0 m')
def test_is_fs_type(self):
test_json = json.loads('{"type": 2077, "typeName": "BTFSValueMapEntry", "message": {}}')
self.assertTrue(parse.is_fs_type(test_json, "BTFSValueMapEntry"))
self.assertFalse(parse.is_fs_type(test_json, "BTFSValueNumber"))
self.assertFalse(parse.is_fs_type(None, "BTFSValueNumber"))
def test_merge_index_sections(self):
new_section = ['test_line', 'test_line2']
old_section = ['test_line', 'test_line3']
result = parse.merge_index_sections(new_section, old_section)
self.assertEqual(result, ['test_line', 'test_line2', 'test_line3'])
def test_find_index_section_limits(self):
index0 = '../rst_files/index_lfom.rst'
_, limits0 = parse.find_index_section_limits(index0)
index1 = '../rst_files/index_lfom_ET.rst'
_, limits1 = parse.find_index_section_limits(index1)
self.assertEqual(limits0, [[18, 26], [27, 32]])
self.assertEqual(limits1, [[18, 26], [27, 33]])
def test_merge_indexes(self):
old_index = '../rst_files/index_lfom.rst'
new_index = '../rst_files/new_index_ET.rst'
parse.merge_indexes(new_index, old_index)
index_file = open(old_index, "r+")
lines = index_file.readlines()
test_file = open('../rst_files/index_lfom_ET.rst')
test_lines = test_file.readlines()
self.assertEqual(test_lines, lines)
old_index = '../rst_files/index_ET.rst'
new_index = '../rst_files/index_floc.rst'
parse.merge_indexes(new_index, old_index)
index_file = open(old_index, "r+")
lines = index_file.readlines()
test_file = open('../rst_files/index_ET_floc.rst')
test_lines = test_file.readlines()
def test_find_treatment_section_limits(self):
process0 = '../rst_files/Treatment_Process_ET.rst'
_, limits0 = parse.find_treatment_section_limits(process0)
process1 = '../rst_files/Treatment_Process_ET_Floc.rst'
lines, limits1 = parse.find_treatment_section_limits(process1)
self.assertEqual(limits0, [[0, 14], [15, 20]])
self.assertEqual(limits1, [[0, 14], [15, 20], [21, 26]])
def test_merge_treatment_processes(self):
old_processes = '../rst_files/Treatment_Process_ET.rst'
new_processes = '../rst_files/Treatment_Process_Floc.rst'
parse.merge_treatment_processes(new_processes, old_processes)
file = open(old_processes, "r+")
lines = file.readlines()
test_file = open('../rst_files/Treatment_Process_ET_Floc.rst')
test_lines = test_file.readlines()
self.assertEqual(test_lines, lines)
def test_get_parsed_measurements(self):
link = 'https://cad.onshape.com/documents/c3a8ce032e33ebe875b9aab4/v/dc76b3f674d3d5d4f6237f35/e/d75b2f7a41dde39791b154e8'
measurements, templates, processes = parse.get_parsed_measurements(
link,
fields=['variables', 'template', 'process'],
for_docs=False
)
self.assertEqual(templates, ['./Entrance_Tank/LFOM.rst'])
self.assertEqual(processes, ['ET'])
self.assertEqual(measurements['N.LfomOrifices'],
[17.0, 4.0, 6.0, 3.0, 4.0, 3.0, 3.0, 3.0, 3.0, 2.0, 3.0, 1.0])
self.assertEqual(measurements['HL.Lfom'], 0.2 * u.m)
self.assertEqual(
measurements['H.LfomOrifices'],
[0.0079375 * u.m, 0.02467613636363637 * u.m,
0.04141477272727274 * u.m, 0.0581534090909091 * u.m,
0.07489204545454548 * u.m, 0.09163068181818185 * u.m,
0.1083693181818182 * u.m, 0.1251079545454546 * u.m,
0.14184659090909096 * u.m, 0.15858522727272734 * u.m,
0.1753238636363637 * u.m, 0.19206250000000008 * u.m]
)
self.assertEqual(measurements['D.LfomOrifices'], 0.015875 * u.m)
self.assertEqual(measurements['B.LfomRows'], 0.016666666666666666 * u.m)
def test_make_replace_list(self):
var_dict = {'test': '3.0 cm'}
file_path = "../rst_files/test_prepend.rst"
parse.make_replace_list(var_dict, file_path)
file = open(file_path, "r+")
lines = file.readlines()
test_file = open('../rst_files/test_prepend_result.rst')
test_lines = test_file.readlines()
self.assertEqual(test_lines, lines)
def test_copy_to_docs(self):
file_path = "Mix/Mix_Design_Data.rst"
parse.copy_to_docs(file_path, base="rst_files")
assert os.path.exists(file_path)
|
class OnshapeParserTest(unittest.TestCase):
def test_parse_quanity(self):
pass
def test_is_fs_type(self):
pass
def test_merge_index_sections(self):
pass
def test_find_index_section_limits(self):
pass
def test_merge_indexes(self):
pass
def test_find_treatment_section_limits(self):
pass
def test_merge_treatment_processes(self):
pass
def test_get_parsed_measurements(self):
pass
def test_make_replace_list(self):
pass
def test_copy_to_docs(self):
pass
| 11 | 0 | 14 | 1 | 12 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 10 | 0 | 10 | 82 | 145 | 20 | 125 | 56 | 114 | 0 | 99 | 56 | 88 | 1 | 2 | 0 | 10 |
3,237 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_physchem.py
|
test_physchem.GeometryTest
|
class GeometryTest(QuantityTest):
"""Test the circular area and diameter functions."""
def test_area_circle(self):
"""area_circle should should give known result with known input."""
checks = ((1*u.m, 0.7853981633974483*u.m**2),
(495.6*u.m, 192908.99423885669*u.m**2),
(495.6*u.m, 192908.99423885669*u.m**2))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.area_circle(i[0]), i[1])
def test_area_circle_range(self):
"""area_circle should return errors with inputs <= 0."""
checks = (0*u.m, -3*u.m)
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.area_circle, i)
def test_diam_circle(self):
"""diam_circle should should give known result with known input."""
checks = ((1 * u.m**2, 1.1283791670955126 * u.m),
(0.1 * u.m**2, 0.3568248232305542 * u.m),
(347 * u.m**2, 21.019374919894773 * u.m),
(10000 * u.m**2, 112.83791670955126 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.diam_circle(i[0]), i[1])
def test_diam_circle_range(self):
"""diam_circle should return errors with inputs <= 0."""
checks = ((0*u.m, ValueError),
(-3*u.m, ValueError))
for i in checks:
with self.subTest(i=i):
self.assertRaises(i[1], pc.diam_circle, i[0])
|
class GeometryTest(QuantityTest):
'''Test the circular area and diameter functions.'''
def test_area_circle(self):
'''area_circle should should give known result with known input.'''
pass
def test_area_circle_range(self):
'''area_circle should return errors with inputs <= 0.'''
pass
def test_diam_circle(self):
'''diam_circle should should give known result with known input.'''
pass
def test_diam_circle_range(self):
'''diam_circle should return errors with inputs <= 0.'''
pass
| 5 | 5 | 8 | 0 | 7 | 1 | 2 | 0.19 | 1 | 1 | 0 | 0 | 4 | 0 | 4 | 77 | 36 | 4 | 27 | 13 | 22 | 5 | 21 | 13 | 16 | 2 | 3 | 2 | 8 |
3,238 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_physchem.py
|
test_physchem.GasTest
|
class GasTest(QuantityTest):
def test_density_air(self):
self.assertWarns(UserWarning, pc.density_air, *(1*u.atm, 28.97*u.g/u.mol, 273*u.K))
def test_density_gas(self):
"""Test the gas density function"""
answer = 1.29320768*u.kg/u.m**3
self.assertAlmostEqualQuantity(pc.density_gas(1*u.atm, 28.97*u.g/u.mol, 273*u.K), answer)
answer = 2.06552481*u.kg/u.m**3
self.assertAlmostEqualQuantity(pc.density_gas(5*u.atm, 10*u.g/u.mol, 295*u.K), answer)
answer = 1.62487951*u.kg/u.m**3
self.assertAlmostEqualQuantity(pc.density_gas(101325*u.Pa, 40*u.g/u.mol, 300*u.K), answer)
answer = 0.20786108*u.kg/u.m**3
self.assertAlmostEqualQuantity(pc.density_gas(700*u.mmHg, 5*u.g/u.mol, 270*u.K), answer)
answer = 0*u.kg/u.m**3
self.assertAlmostEqualQuantity(pc.density_gas(0*u.atm, 28.97*u.g/u.mol, 273*u.K), answer)
|
class GasTest(QuantityTest):
def test_density_air(self):
pass
def test_density_gas(self):
'''Test the gas density function'''
pass
| 3 | 1 | 7 | 0 | 7 | 1 | 1 | 0.07 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 75 | 17 | 2 | 14 | 4 | 11 | 1 | 14 | 4 | 11 | 1 | 3 | 0 | 2 |
3,239 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_physchem.py
|
test_physchem.FrictionFuncsTest
|
class FrictionFuncsTest(QuantityTest):
"""Test the friction functions."""
def test_fric(self):
self.assertWarns(UserWarning, pc.fric, *(100 * u.m**3/u.s, 2 * u.m, 0.001 * u.m**2/u.s, 1 * u.m))
def test_fric_pipe(self):
"""fric_pipe should return known results with known input."""
checks = (([100 * u.m**3/u.s, 2 * u.m, 0.001 * u.m**2/u.s, 1 * u.m], 0.33154589118654193),
([100 * u.m**3/u.s, 2 * u.m, 0.1 * u.m**2/u.s, 1 * u.m], 0.10053096491487337),
([100 * u.m**3/u.s, 2 * u.m, 0.001 * u.m**2/u.s, 0 * u.m], 0.019675384283293733),
([46 * u.m**3/u.s, 9 * u.m, 0.001 * u.m**2/u.s, 0.03 * u.m], 0.039382681891291252),
([55 * u.m**3/u.s, 0.4 * u.m, 0.5 * u.m**2/u.s, 0.0001 * u.m], 0.18278357257249706))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.fric_pipe(*i[0]), i[1] * u.dimensionless)
def test_fric_range(self):
"""fric_pipe should raise an error if 0 <= Roughness is not true."""
checks = ([1 * u.m**3/u.s, 2 * u.m, 0.1 * u.m**2/u.s, -0.1 * u.m],)
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.fric_pipe, *i)
def test_fric_rect(self):
"""fric_rect should return known results with known inputs."""
checks = (([60 * u.m**3/u.s, 0.7 * u.m, 1 * u.m, 0.6 * u.m**2/u.s, 0.001 * u.m, True], 0.432),
([60 * u.m**3/u.s, 0.7 * u.m, 1 * u.m, 0.6 * u.m**2/u.s, 0.001 * u.m, False], 0.544),
([120 * u.m**3/u.s, 1 * u.m, 0.04 * u.m, 0.125 * u.m**2/u.s, 0.6 * u.m, True], 150.90859874356411),
([120 * u.m**3/u.s, 1 * u.m, 0.04 * u.m, 0.125 * u.m**2/u.s, 0.6 * u.m, False], 0.034666666666666665),
([120 * u.m**3/u.s, 1 * u.m, 0.04 * u.m, 0.125 * u.m**2/u.s, 0 * u.m, False], 0.034666666666666665),
([120 * u.m**3/u.s, 1 * u.m, 0.04 * u.m, 0.125 * u.m**2/u.s, 0 * u.m, True], 0.042098136441473824))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.fric_rect(*i[0]), i[1] * u.dimensionless)
def test_fric_rect_range(self):
"""fric_rect should raise an error if 0 <= Roughness not true."""
checks = ([1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, -1.1 * u.m, True],)
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.fric_rect, *i)
def test_fric_rect_warning(self):
"""fric_rect should raise warnings when passed deprecated parameters"""
error_checks = (lambda: pc.fric_rect(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, Roughness=1 * u.m, PipeRough=1 * u.m, OpenChannel=True),
lambda: pc.fric_rect(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, 1 * u.m, OpenChannel=True, openchannel=True))
for i in error_checks:
with self.subTest(i=i):
self.assertRaises(TypeError, i)
warning_checks = (lambda: pc.fric_rect(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, PipeRough=1 * u.m, OpenChannel=True),
lambda: pc.fric_rect(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, PipeRough=1 * u.m, openchannel=True),
lambda: pc.fric_rect(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, 1 * u.m, openchannel=True))
for i in warning_checks:
with self.subTest(i=i):
self.assertWarns(UserWarning, i)
def test_fric_general(self):
self.assertWarns(UserWarning, pc.fric_general, *(9 * u.m**2, 0.67 * u.m, 3 * u.m/u.s, 0.987 * u.m**2/u.s, 0.86 * u.m))
def test_fric_channel(self):
"""fric_channel should return known results with known inputs."""
checks = (([9 * u.m**2, 0.67 * u.m, 3 * u.m/u.s, 0.987 * u.m**2/u.s, 0.86 * u.m], 0.3918755555555556),
([1 * u.m**2, 1 * u.m, 1 * u.m/u.s, 1 * u.m**2/u.s, 1 * u.m], 16),
([120 * u.m**2, 0.6 * u.m, 12 * u.m/u.s, 0.3 * u.m**2/u.s, 0.002 * u.m], 0.023024557179148988))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.fric_channel(*i[0]), i[1] * u.dimensionless)
def test_fric_channel_range(self):
"""fric_channel should raise an error if 0 <= Roughness is not true."""
checks = ((1 * u.m**2, 1 * u.m, 1 * u.m/u.s, 1 * u.m**2/u.s, -0.0001 * u.m),)
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.fric_channel, *i)
|
class FrictionFuncsTest(QuantityTest):
'''Test the friction functions.'''
def test_fric(self):
pass
def test_fric_pipe(self):
'''fric_pipe should return known results with known input.'''
pass
def test_fric_range(self):
'''fric_pipe should raise an error if 0 <= Roughness is not true.'''
pass
def test_fric_rect(self):
'''fric_rect should return known results with known inputs.'''
pass
def test_fric_rect_range(self):
'''fric_rect should raise an error if 0 <= Roughness not true.'''
pass
def test_fric_rect_warning(self):
'''fric_rect should raise warnings when passed deprecated parameters'''
pass
def test_fric_general(self):
pass
def test_fric_channel(self):
'''fric_channel should return known results with known inputs.'''
pass
def test_fric_channel_range(self):
'''fric_channel should raise an error if 0 <= Roughness is not true.'''
pass
| 10 | 8 | 7 | 0 | 6 | 1 | 2 | 0.14 | 1 | 3 | 0 | 0 | 9 | 0 | 9 | 82 | 76 | 10 | 58 | 25 | 48 | 8 | 44 | 25 | 34 | 3 | 3 | 2 | 17 |
3,240 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_physchem.py
|
test_physchem.FlowFuncsTest
|
class FlowFuncsTest(QuantityTest):
"""Test the flow functions."""
def test_flow_transition(self):
"""flow_transition should return known value for known inputs."""
checks = (([2 * u.m, 0.4 * u.m**2/u.s], 1319.4689145077132 * u.m**3/u.s),
([0.8 * u.m, 1.1 * u.m**2/u.s], 1451.4158059584847 * u.m**3/u.s))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.flow_transition(*i[0]), i[1])
def test_flow_transition_range(self):
"""flow_transition should not accept inputs <= 0."""
checks = ((1 * u.m, 0 * u.m**2/u.s), (0 * u.m, 1 * u.m**2/u.s))
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.flow_transition, *i)
def test_flow_hagen(self):
"""flow_hagen should return known value for known inputs."""
checks = (([1 * u.m, 0.4 * u.m, 5.21 * u.m, 0.6 * u.m**2/u.s], 0.03079864403023667 * u.m**3/u.s),
([0.05 * u.m, 0.0006 * u.m, 0.3 * u.m, 1.1 * u.m**2/u.s], 2.7351295806397676e-09 * u.m**3/u.s))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.flow_hagen(*i[0]), i[1])
def test_flow_hagen_range(self):
"""flow_hagen should raise errors when inputs are out of bounds."""
failChecks = ((0 * u.m, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s),
(1 * u.m, -1 * u.m, 1 * u.m, 1 * u.m**2/u.s),
(1 * u.m, 1 * u.m, 0 * u.m, 1 * u.m**2/u.s),
(1 * u.m, 1 * u.m, 1 * u.m, 0 * u.m**2/u.s))
for i in failChecks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.flow_hagen, *i)
passChecks = ((1 * u.m, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s),
(1 * u.m, 0 * u.m, 1 * u.m, 1 * u.m**2/u.s))
for i in passChecks:
with self.subTest(i=i):
pc.flow_hagen(*i)
def test_flow_hagen_warning(self):
"""flow_hagen should raise warnings when passed deprecated parameters"""
error_checks = (lambda: pc.flow_hagen(1 * u.m, HeadLossMajor=1 * u.m, Length=1 * u.m, Nu=1 * u.m**2/u.s, HeadLossFric=1 * u.m),
lambda: pc.flow_hagen(1 * u.m, Length=1 * u.m, Nu=1 * u.m**2/u.s),
lambda: pc.flow_hagen(1 * u.m, HeadLossMajor=1 * u.m, Nu=1 * u.m**2/u.s),
lambda: pc.flow_hagen(1 * u.m, HeadLossMajor=1 * u.m, Length=1 * u.m))
for i in error_checks:
with self.subTest(i=i):
self.assertRaises(TypeError, i)
warning_checks = (lambda: pc.flow_hagen(1 * u.m, HeadLossFric=1 * u.m, Length=1 * u.m, Nu=1 * u.m**2/u.s),)
for i in warning_checks:
with self.subTest(i=i):
self.assertWarns(UserWarning, i)
def test_flow_swamee(self):
"""flow_swamee should return known value for known inputs."""
checks = (([2 * u.m, 0.04 * u.m, 3 * u.m, 0.1 * u.m**2/u.s, 0.37 * u.m], 2.9565931732010045 * u.m**3/u.s),)
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.flow_swamee(*i[0]), i[1])
def test_flow_swamee_range(self):
"""flow_swamee should raise errors when inputs are out of bounds."""
failChecks = ((0 * u.m, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, 1 * u.m),
(1 * u.m, 0 * u.m, 1 * u.m, 1 * u.m**2/u.s, 1 * u.m),
(1 * u.m, 1 * u.m, 0 * u.m, 1 * u.m**2/u.s, 1 * u.m),
(1 * u.m, 1 * u.m, 1 * u.m, 0 * u.m**2/u.s, 1 * u.m),
(1 * u.m, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, -0.1 * u.m),
(1 * u.m, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, -2 * u.m))
for i in failChecks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.flow_swamee, *i)
passChecks = ((1 * u.m, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, 1 * u.m),
(1 * u.m, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, 0 * u.m))
for i in passChecks:
with self.subTest(i=i):
pc.flow_swamee(*i)
def test_flow_swamee_warning(self):
"""flow_swamee should raise warnings when passed deprecated parameters"""
error_checks = (lambda: pc.flow_swamee(1 * u.m, HeadLossMajor=1 * u.m, Length=1 * u.m, Nu=1 * u.m**2/u.s, Roughness=1 * u.m, HeadLossFric=1 * u.m),
lambda: pc.flow_swamee(1 * u.m, Length=1 * u.m, Nu=1 * u.m**2/u.s, Roughness=1 * u.m),
lambda: pc.flow_swamee(1 * u.m, HeadLossMajor=1 * u.m, Nu=1 * u.m**2/u.s, Roughness=1 * u.m),
lambda: pc.flow_swamee(1 * u.m, HeadLossMajor=1 * u.m, Length=1 * u.m, Roughness=1 * u.m),
lambda: pc.flow_swamee(1 * u.m, HeadLossMajor=1 * u.m, Length=1 * u.m, Nu=1 * u.m**2/u.s, Roughness=1 * u.m, PipeRough=1 * u.m),
lambda: pc.flow_swamee(1 * u.m, HeadLossMajor=1 * u.m, Length=1 * u.m, Nu=1 * u.m**2/u.s))
for i in error_checks:
with self.subTest(i=i):
self.assertRaises(TypeError, i)
warning_checks = (lambda: pc.flow_swamee(1 * u.m, HeadLossFric=1 * u.m, Length=1 * u.m, Nu=1 * u.m**2/u.s, Roughness=1 * u.m),
lambda: pc.flow_swamee(1 * u.m, HeadLossMajor=1 * u.m, Length=1 * u.m, Nu=1 * u.m**2/u.s, PipeRough=1 * u.m))
for i in warning_checks:
with self.subTest(i=i):
self.assertWarns(UserWarning, i)
def test_flow_pipemajor(self):
self.assertWarns(UserWarning, pc.flow_pipemajor, *(1 * u.m, 0.97 * u.m, 0.5 * u.m, 0.025 * u.m**2/u.s, 0.06 * u.m))
def test_flow_major_pipe(self):
"""flow_major_pipe should return known result for known inputs."""
checks = (([1 * u.m, 0.97 * u.m, 0.5 * u.m, 0.025 * u.m**2/u.s, 0.06 * u.m], 18.677652880272845 * u.m**3/u.s),
([2 * u.m, 0.62 * u.m, 0.5 * u.m, 0.036 * u.m**2/u.s, 0.23 * u.m], 62.457206502701297 * u.m**3/u.s))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.flow_major_pipe(*i[0]), i[1])
def test_flow_pipeminor(self):
self.assertWarns(UserWarning, pc.flow_pipeminor, *(1 * u.m, 0.125 * u.m, 3))
def test_flow_minor_pipe(self):
"""flow_minor_pipe should return known results for known input."""
self.assertAlmostEqualQuantity(pc.flow_minor_pipe(1 * u.m, 0.125 * u.m, 3),
0.71000203931611083 * u.m**3/u.s)
def test_flow_minor_pipe_range(self):
"""flow_minor_pipe should raise errors when inputs are out of bounds."""
failChecks = ((1 * u.m, -1 * u.m, 1),
(1 * u.m, 1 * u.m, 0 * u.dimensionless))
for i in failChecks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.flow_minor_pipe, *i)
passChecks = ((1 * u.m, 1 * u.m, 1), (1 * u.m, 0 * u.m, 1))
for i in passChecks:
with self.subTest(i=i):
pc.flow_minor_pipe(*i)
def test_flow_pipe(self):
"""flow_pipe should return known value for known inputs."""
checks = (([0.25 * u.m, 0.4 * u.m, 2 * u.m, 0.58 * u.m**2/u.s, 0.029 * u.m, 0], 0.000324207170118938 * u.m**3/u.s),
([0.25 * u.m, 0.4 * u.m, 2 * u.m, 0.58 * u.m**2/u.s, 0.029 * u.m, 0.35 * u.dimensionless], 0.000324206539183988 * u.m**3/u.s))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.flow_pipe(*i[0]), i[1])
def test_flow_pipe_warning(self):
"""flow_pipe should raise warnings when passed deprecated parameters"""
error_checks = (lambda: pc.flow_pipe(1 * u.m, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, Roughness=1 * u.m, KMinor=1, PipeRough=1 * u.m),
lambda: pc.flow_pipe(1 * u.m, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, KMinor=1),
lambda: pc.flow_pipe(1 * u.m, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, Roughness=1 * u.m),)
for i in error_checks:
with self.subTest(i=i):
self.assertRaises(TypeError, i)
warning_checks = (lambda: pc.flow_pipe(1 * u.m, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, PipeRough=1 * u.m, KMinor=1),)
for i in warning_checks:
with self.subTest(i=i):
self.assertWarns(UserWarning, i)
|
class FlowFuncsTest(QuantityTest):
'''Test the flow functions.'''
def test_flow_transition(self):
'''flow_transition should return known value for known inputs.'''
pass
def test_flow_transition_range(self):
'''flow_transition should not accept inputs <= 0.'''
pass
def test_flow_hagen(self):
'''flow_hagen should return known value for known inputs.'''
pass
def test_flow_hagen_range(self):
'''flow_hagen should raise errors when inputs are out of bounds.'''
pass
def test_flow_hagen_warning(self):
'''flow_hagen should raise warnings when passed deprecated parameters'''
pass
def test_flow_swamee(self):
'''flow_swamee should return known value for known inputs.'''
pass
def test_flow_swamee_range(self):
'''flow_swamee should raise errors when inputs are out of bounds.'''
pass
def test_flow_swamee_warning(self):
'''flow_swamee should raise warnings when passed deprecated parameters'''
pass
def test_flow_pipemajor(self):
pass
def test_flow_major_pipe(self):
'''flow_major_pipe should return known result for known inputs.'''
pass
def test_flow_pipeminor(self):
pass
def test_flow_minor_pipe(self):
'''flow_minor_pipe should return known results for known input.'''
pass
def test_flow_minor_pipe_range(self):
'''flow_minor_pipe should raise errors when inputs are out of bounds.'''
pass
def test_flow_pipemajor(self):
'''flow_pipe should return known value for known inputs.'''
pass
def test_flow_pipe_warning(self):
'''flow_pipe should raise warnings when passed deprecated parameters'''
pass
| 16 | 14 | 9 | 0 | 8 | 1 | 2 | 0.12 | 1 | 3 | 0 | 0 | 15 | 0 | 15 | 88 | 149 | 17 | 118 | 46 | 102 | 14 | 91 | 46 | 75 | 3 | 3 | 2 | 33 |
3,241 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_physchem.py
|
test_physchem.DiamFuncsTest
|
class DiamFuncsTest(QuantityTest):
"""Test the diameter functions."""
def test_diam_hagen(self):
"""diam_hagen should return known value for known inputs."""
self.assertAlmostEqualQuantity(pc.diam_hagen(0.006 * u.m**3/u.s, 0.00025 * u.m, 0.75 * u.m, 0.0004 * u.m**2/u.s),
0.4158799465199102 * u.m)
def test_diam_hagen_range(self):
"""diam_hagen should raise errors when inputs are out of bounds."""
failChecks = ((0 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s),
(1 * u.m**3/u.s, 0 * u.m, 1 * u.m, 1 * u.m**2/u.s),
(1 * u.m**3/u.s, 1 * u.m, 0 * u.m, 1 * u.m**2/u.s),
(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 0 * u.m**2/u.s))
for i in failChecks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.diam_hagen, *i)
def test_diam_hagen_warning(self):
"""flow_hagen should raise warnings when passed deprecated parameters"""
error_checks = (lambda: pc.diam_hagen(1 * u.m**3/u.s, HeadLossMajor=1 * u.m, Length=1 * u.m, Nu=1 * u.m**2/u.s, HeadLossFric=1 * u.m),
lambda: pc.diam_hagen(1 * u.m**3/u.s, Length=1 * u.m, Nu=1 * u.m**2/u.s),
lambda: pc.diam_hagen(1 * u.m**3/u.s, HeadLossMajor=1 * u.m, Nu=1 * u.m**2/u.s),
lambda: pc.diam_hagen(1 * u.m**3/u.s, HeadLossMajor=1 * u.m, Length=1 * u.m))
for i in error_checks:
with self.subTest(i=i):
self.assertRaises(TypeError, i)
warning_checks = (lambda: pc.diam_hagen(1 * u.m**3/u.s, HeadLossFric=1 * u.m, Length=1 * u.m, Nu=1 * u.m**2/u.s),)
for i in warning_checks:
with self.subTest(i=i):
self.assertWarns(UserWarning, i)
def test_diam_swamee(self):
"""diam_swamee should return known value for known input."""
self.assertAlmostEqualQuantity(pc.diam_swamee(0.06 * u.m**3/u.s, 1.2 * u.m, 7 * u.m, 0.2* u.m**2/u.s, 0.0004 * u.m),
0.19286307314945772 * u.m)
def test_diam_swamee_range(self):
"""diam_swamee should raise errors if inputs are out of bounds."""
failChecks = ((0 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, 1 * u.m),
(1 * u.m**3/u.s, 0 * u.m, 1 * u.m, 1 * u.m**2/u.s, 1 * u.m),
(1 * u.m**3/u.s, 1 * u.m, 0 * u.m, 1 * u.m**2/u.s, 1 * u.m),
(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 0 * u.m**2/u.s, 1 * u.m),
(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, -2 * u.m),
(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, -1 * u.m))
for i in failChecks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.diam_swamee, *i)
passChecks = ((1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, 1 * u.m),
(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, 0 * u.m))
for i in passChecks:
with self.subTest(i=i):
pc.diam_swamee(*i)
def test_diam_swamee_warning(self):
"""diam_swamee should raise warnings when passed deprecated parameters"""
error_checks = (lambda: pc.diam_swamee(1 * u.m**3/u.s, HeadLossMajor=1 * u.m, Length=1 * u.m, Nu=1 * u.m**2/u.s, Roughness=1 * u.m, HeadLossFric=1 * u.m),
lambda: pc.diam_swamee(1 * u.m**3/u.s, Length=1 * u.m, Nu=1 * u.m**2/u.s, Roughness=1 * u.m),
lambda: pc.diam_swamee(1 * u.m**3/u.s, HeadLossMajor=1 * u.m, Nu=1 * u.m**2/u.s, Roughness=1 * u.m),
lambda: pc.diam_swamee(1 * u.m**3/u.s, HeadLossMajor=1 * u.m, Length=1 * u.m, Roughness=1 * u.m),
lambda: pc.diam_swamee(1 * u.m**3/u.s, HeadLossMajor=1 * u.m, Length=1 * u.m, Nu=1 * u.m**2/u.s, Roughness=1 * u.m, PipeRough=1 * u.m),
lambda: pc.diam_swamee(1 * u.m**3/u.s, HeadLossMajor=1 * u.m, Length=1 * u.m, Nu=1 * u.m**2/u.s))
for i in error_checks:
with self.subTest(i=i):
self.assertRaises(TypeError, i)
warning_checks = (lambda: pc.diam_swamee(1 * u.m**3/u.s, HeadLossFric=1 * u.m, Length=1 * u.m, Nu=1 * u.m**2/u.s, Roughness=1 * u.m),
lambda: pc.diam_swamee(1 * u.m**3/u.s, HeadLossMajor=1 * u.m, Length=1 * u.m, Nu=1 * u.m**2/u.s, PipeRough=1 * u.m))
for i in warning_checks:
with self.subTest(i=i):
self.assertWarns(UserWarning, i)
def test_diam_pipemajor(self):
self.assertWarns(UserWarning, pc.diam_pipemajor, *(0.005 * u.m**3/u.s, 0.03 * u.m, 1.6 * u.m, 0.53 * u.m**2/u.s, 0.002 * u.m))
def test_diam_major_pipe(self):
"""diam_major_pipe should return known value for known inputs."""
checks = (([0.005 * u.m**3/u.s, 0.03 * u.m, 1.6 * u.m, 0.53 * u.m**2/u.s, 0.002 * u.m], 0.8753787620849313 * u.m),
([1 * u.m**3/u.s, 2 * u.m, 0.03 * u.m, 0.004 * u.m**2/u.s, 0.005 * u.m], 0.14865504303291951 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.diam_major_pipe(*i[0]), i[1])
def test_diam_pipeminor(self):
self.assertWarns(UserWarning, pc.diam_pipeminor, *(0.008 * u.m**3/u.s, 0.012 * u.m, 0.93))
def test_diam_minor_pipe(self):
"""diam_minor_pipe should return known value for known inputs."""
checks = (([0.008 * u.m**3/u.s, 0.012 * u.m, 0.93], 0.14229440061589257 * u.m),
([0.015 * u.m**3/u.s, 0.3 * u.m, 0.472 * u.dimensionless], 0.073547549463488848 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.diam_minor_pipe(*i[0]), i[1])
def test_diam_minor_pipe_range(self):
"""diam_minor_pipe should raise errors when inputs are out of bounds."""
failChecks = ((0 * u.m**3/u.s, 1 * u.m, 1),
(1 * u.m**3/u.s, 0 * u.m, 1),
(1 * u.m**3/u.s, 1 * u.m, -1 * u.dimensionless))
for i in failChecks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.diam_minor_pipe, *i)
passChecks = ((1 * u.m**3/u.s, 1 * u.m, 1),
(1 * u.m**3/u.s, 1 * u.m, 0))
for i in passChecks:
with self.subTest(i=i):
pc.diam_minor_pipe(*i)
def test_diam_pipe(self):
"""diam_pipe should return known value for known inputs."""
checks = (([0.007 * u.m**3/u.s, 0.04 * u.m, 0.75 * u.m, 0.16 * u.m**2/u.s, 0.0079 * u.m, 0], 0.5434876490369928 * u.m),
([0.007 * u.m**3/u.s, 0.04 * u.m, 0.75 * u.m, 0.16 * u.m**2/u.s, 0.0079 * u.m, 0.8 * u.dimensionless], 0.5436137491479152 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.diam_pipe(*i[0]), i[1])
|
class DiamFuncsTest(QuantityTest):
'''Test the diameter functions.'''
def test_diam_hagen(self):
'''diam_hagen should return known value for known inputs.'''
pass
def test_diam_hagen_range(self):
'''diam_hagen should raise errors when inputs are out of bounds.'''
pass
def test_diam_hagen_warning(self):
'''flow_hagen should raise warnings when passed deprecated parameters'''
pass
def test_diam_swamee(self):
'''diam_swamee should return known value for known input.'''
pass
def test_diam_swamee_range(self):
'''diam_swamee should raise errors if inputs are out of bounds.'''
pass
def test_diam_swamee_warning(self):
'''diam_swamee should raise warnings when passed deprecated parameters'''
pass
def test_diam_pipemajor(self):
pass
def test_diam_major_pipe(self):
'''diam_major_pipe should return known value for known inputs.'''
pass
def test_diam_pipeminor(self):
pass
def test_diam_minor_pipe(self):
'''diam_minor_pipe should return known value for known inputs.'''
pass
def test_diam_minor_pipe_range(self):
'''diam_minor_pipe should raise errors when inputs are out of bounds.'''
pass
def test_diam_pipemajor(self):
'''diam_pipe should return known value for known inputs.'''
pass
| 13 | 11 | 9 | 0 | 8 | 1 | 2 | 0.12 | 1 | 3 | 0 | 0 | 12 | 0 | 12 | 85 | 115 | 13 | 91 | 33 | 78 | 11 | 65 | 33 | 52 | 3 | 3 | 2 | 24 |
3,242 |
AguaClara/aguaclara
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AguaClara_aguaclara/aguaclara/research/stock_qc.py
|
aguaclara.research.stock_qc.Variable_C_Stock
|
class Variable_C_Stock(Stock):
"""A flow reactor with input from a stock of material of unknown
concentration.
:Examples:
>>> from aguaclara.research.stock_qc import Variable_C_Stock
>>> from aguaclara.core.units import u
>>> reactor = Variable_C_Stock(Q_sys = 1*u.mL/u.s, C_sys = 1.4*u.mg/u.L, Q_stock = .01*u.mL/u.s)
>>> reactor.C_stock()
<Quantity(140.0, 'milligram / liter')>
"""
def __init__(self, Q_sys, C_sys, Q_stock):
"""Initialize a reactor of unknown material stock concentration.
:param Q_sys: Flow rate of the system
:type Q_sys: float
:param C_sys: Concentration of the material in the system
:type C_sys: float
:param Q_stock: Flow rate from the stock of material
:type Q_stock: float
"""
self._Q_sys = Q_sys
self._C_sys = C_sys
self._Q_stock = Q_stock
def Q_sys(self):
"""Return the flow rate of the system.
:return: Flow rate of the system
:rtype: float
"""
return self._Q_sys
def C_sys(self):
"""Return the concentration of the material in the system.
:return: Concentration of the material in the system
:rtype: float
"""
return self._C_sys
def Q_stock(self):
"""Return the flow rate from the stock of material.
:return: Flow rate from the stock of material
:rtype: float
"""
return self._Q_stock
def C_stock(self):
"""Return the required concentration of material in the stock given a
reactor's desired system flow rate, system concentration, and stock
flow rate.
:return: Concentration of material in the stock
:rtype: float
"""
return self._C_sys * (self._Q_sys / self._Q_stock).to(u.dimensionless)
@ut.list_handler()
def rpm(self, vol_per_rev):
"""Return the pump speed required for the reactor's stock of material
given the volume of fluid output per revolution by the stock's pump.
:param vol_per_rev: Volume of fluid pumped per revolution (dependent on pump and tubing)
:type vol_per_rev: float
:return: Pump speed for the material stock, in revolutions per minute
:rtype: float
"""
return Stock.rpm(self, vol_per_rev, self._Q_stock).to(u.rev/u.min)
@ut.list_handler()
def T_stock(self, V_stock):
"""Return the amount of time at which the stock of materal will be
depleted.
:param V_stock: Volume of the stock of material
:type V_stock: float
:return: Time at which the stock will be depleted
:rtype: float
"""
return Stock.T_stock(self, V_stock, self._Q_stock).to(u.hr)
@ut.list_handler()
def M_stock(self, V_stock):
"""Return the mass of undiluted material required for the stock
concentration.
:param V_stock: Volume of the stock of material
:type V_stock: float
:return: Mass of undiluted stock material
:rtype: float
"""
return Stock.M_stock(self, V_stock, self.C_stock())
@ut.list_handler()
def V_super_stock(self, V_stock, C_super_stock):
"""Return the volume of super (more concentrated) stock that must be
diluted for the desired stock volume and required stock concentration.
:param V_stock: Volume of the stock of material
:type V_stock: float
:param C_super_stock: Concentration of the super stock
:type C_super_stock: float
:return: Volume of super stock to dilute
:rtype: float
"""
return Stock.V_super_stock(self, V_stock, self.C_stock(), C_super_stock)
@ut.list_handler()
def dilution_factor(self, C_super_stock):
"""Return the dilution factor of the concentration of material in the
stock relative to the super stock.
:param C_super_stock: Concentration of the super stock
:type C_super_stock: float
:return: dilution factor of stock concentration over super stock concentration (< 1)
:rtype: float
"""
return Stock.dilution_factor(self, self.C_stock(), C_super_stock)
|
class Variable_C_Stock(Stock):
'''A flow reactor with input from a stock of material of unknown
concentration.
:Examples:
>>> from aguaclara.research.stock_qc import Variable_C_Stock
>>> from aguaclara.core.units import u
>>> reactor = Variable_C_Stock(Q_sys = 1*u.mL/u.s, C_sys = 1.4*u.mg/u.L, Q_stock = .01*u.mL/u.s)
>>> reactor.C_stock()
<Quantity(140.0, 'milligram / liter')>
'''
def __init__(self, Q_sys, C_sys, Q_stock):
'''Initialize a reactor of unknown material stock concentration.
:param Q_sys: Flow rate of the system
:type Q_sys: float
:param C_sys: Concentration of the material in the system
:type C_sys: float
:param Q_stock: Flow rate from the stock of material
:type Q_stock: float
'''
pass
def Q_sys(self):
'''Return the flow rate of the system.
:return: Flow rate of the system
:rtype: float
'''
pass
def C_sys(self):
'''Return the concentration of the material in the system.
:return: Concentration of the material in the system
:rtype: float
'''
pass
def Q_stock(self):
'''Return the flow rate from the stock of material.
:return: Flow rate from the stock of material
:rtype: float
'''
pass
def C_stock(self):
'''Return the required concentration of material in the stock given a
reactor's desired system flow rate, system concentration, and stock
flow rate.
:return: Concentration of material in the stock
:rtype: float
'''
pass
@ut.list_handler()
def rpm(self, vol_per_rev):
'''Return the pump speed required for the reactor's stock of material
given the volume of fluid output per revolution by the stock's pump.
:param vol_per_rev: Volume of fluid pumped per revolution (dependent on pump and tubing)
:type vol_per_rev: float
:return: Pump speed for the material stock, in revolutions per minute
:rtype: float
'''
pass
@ut.list_handler()
def T_stock(self, V_stock):
'''Return the amount of time at which the stock of materal will be
depleted.
:param V_stock: Volume of the stock of material
:type V_stock: float
:return: Time at which the stock will be depleted
:rtype: float
'''
pass
@ut.list_handler()
def M_stock(self, V_stock):
'''Return the mass of undiluted material required for the stock
concentration.
:param V_stock: Volume of the stock of material
:type V_stock: float
:return: Mass of undiluted stock material
:rtype: float
'''
pass
@ut.list_handler()
def V_super_stock(self, V_stock, C_super_stock):
'''Return the volume of super (more concentrated) stock that must be
diluted for the desired stock volume and required stock concentration.
:param V_stock: Volume of the stock of material
:type V_stock: float
:param C_super_stock: Concentration of the super stock
:type C_super_stock: float
:return: Volume of super stock to dilute
:rtype: float
'''
pass
@ut.list_handler()
def dilution_factor(self, C_super_stock):
'''Return the dilution factor of the concentration of material in the
stock relative to the super stock.
:param C_super_stock: Concentration of the super stock
:type C_super_stock: float
:return: dilution factor of stock concentration over super stock concentration (< 1)
:rtype: float
'''
pass
| 16 | 11 | 10 | 2 | 2 | 6 | 1 | 2.57 | 1 | 0 | 0 | 0 | 10 | 3 | 10 | 15 | 127 | 27 | 28 | 19 | 12 | 72 | 23 | 14 | 12 | 1 | 2 | 0 | 10 |
3,243 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_head_loss.py
|
test_head_loss.KValuesCalculationTest
|
class KValuesCalculationTest(unittest.TestCase):
def assertAlmostEqualQuantity(self, first, second, places=7):
self.assertAlmostEqual(first.magnitude, second.magnitude, places)
self.assertEqual(first.units, second.units, places)
# Test Reductions
def test_k_value_reduction_square_turbulent(self):
self.assertAlmostEqualQuantity(k.k_value_reduction(pipe.OD(4*u.inch), pipe.OD(2*u.inch), 4 * u.L / u.s),
5.689246477984541*u.dimensionless)
def test_k_value_reduction_laminar(self):
self.assertAlmostEqualQuantity(k.k_value_reduction(pipe.OD(1*u.inch), pipe.OD(0.5*u.inch), 0.1 * u.L / u.s),
2.2100363820127233*u.dimensionless)
def test_k_value_reduction_from_very_large_pipe_turbulent(self):
self.assertAlmostEqualQuantity(k.k_value_reduction(pipe.OD(400*u.inch), pipe.OD(4*u.inch), 4 * u.L / u.s),
222469.482*u.dimensionless, 2)
# Test Expansions
def test_k_value_expansion_into_large_tank(self):
self.assertAlmostEqualQuantity(k.k_value_expansion(pipe.OD(4*u.inch), pipe.OD(400*u.inch), 4 * u.L / u.s),
1.0148940670855733*u.dimensionless)
def test_k_value_expansion_into_very_large_pipe_laminar(self):
self.assertAlmostEqualQuantity(k.k_value_expansion(pipe.OD(1*u.inch), pipe.OD(400*u.inch), 0.1 * u.L / u.s),
1.9999999165201428*u.dimensionless)
# Test Orifices
# Test private functions
def test_k_value_thick_orifice_high_headloss(self):
self.assertAlmostEqual(k._k_value_thick_orifice(0.02, 0.002, 0.000002, 2),
1594340.3320537778)
def test_k_value_thin_orifice_high_headloss(self):
self.assertAlmostEqual(k._k_value_thin_sharp_orifice(0.02, 0.002, 2),
1594433.5406999998)
# Test public function
def test_k_value_thin_orifice_regular_high_headloss(self):
self.assertAlmostEqualQuantity(k.k_value_orifice(0.02 * u.m, 0.002 * u.m, 0 * u.m, 1*u.L/u.s),
1697.9866773221295*u.dimensionless)
def test_k_value_super_thick_orifice_high_headloss(self):
self.assertAlmostEqualQuantity(k.k_value_orifice(pipe.OD(6*u.inch), pipe.OD(4*u.inch), 60*u.inch, 1 * u.L / u.s),
1.8577290828680884*u.dimensionless)
def test_k_value_thin_orifice(self):
self.assertAlmostEqualQuantity(k.k_value_orifice(pipe.OD(6*u.inch), pipe.OD(4*u.inch), 0*u.inch, 1 * u.L / u.s),
3.3497584836648246*u.dimensionless)
def test_k_value_thick_orifice(self):
self.assertAlmostEqualQuantity(k.k_value_orifice(pipe.OD(6*u.inch), pipe.OD(4*u.inch), 1*u.inch, 1 * u.L / u.s),
2.9070736824641181*u.dimensionless)
|
class KValuesCalculationTest(unittest.TestCase):
def assertAlmostEqualQuantity(self, first, second, places=7):
pass
def test_k_value_reduction_square_turbulent(self):
pass
def test_k_value_reduction_laminar(self):
pass
def test_k_value_reduction_from_very_large_pipe_turbulent(self):
pass
def test_k_value_expansion_into_large_tank(self):
pass
def test_k_value_expansion_into_very_large_pipe_laminar(self):
pass
def test_k_value_thick_orifice_high_headloss(self):
pass
def test_k_value_thin_orifice_high_headloss(self):
pass
def test_k_value_thin_orifice_regular_high_headloss(self):
pass
def test_k_value_super_thick_orifice_high_headloss(self):
pass
def test_k_value_thin_orifice_high_headloss(self):
pass
def test_k_value_thick_orifice_high_headloss(self):
pass
| 13 | 0 | 3 | 0 | 3 | 0 | 1 | 0.14 | 1 | 0 | 0 | 0 | 12 | 0 | 12 | 84 | 55 | 13 | 37 | 13 | 24 | 5 | 26 | 13 | 13 | 1 | 2 | 0 | 12 |
3,244 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_cache.py
|
test_cache.ComputedObject
|
class ComputedObject(HashableObject):
def __init__(self):
self.a = 2
self.b = 3
self.c = 4
@property
@ac_cache
def product(self):
increment_n_calls()
return self.a * self.b * self.c
@property
@ac_cache
def sum(self):
increment_n_calls()
return self.a + self.b + self.c
@ac_cache
def sum_with_arg(self, my_arg):
increment_n_calls()
return self.sum + my_arg
@ac_cache
def sum_with_kwarg(self, my_arg=10):
increment_n_calls()
return self.sum + my_arg
|
class ComputedObject(HashableObject):
def __init__(self):
pass
@property
@ac_cache
def product(self):
pass
@property
@ac_cache
def sum(self):
pass
@ac_cache
def sum_with_arg(self, my_arg):
pass
@ac_cache
def sum_with_kwarg(self, my_arg=10):
pass
| 12 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 5 | 3 | 5 | 6 | 27 | 4 | 23 | 13 | 11 | 0 | 17 | 9 | 11 | 1 | 1 | 0 | 5 |
3,245 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/research/stock_qc.py
|
aguaclara.research.stock_qc.Stock
|
class Stock(object):
"""A stock of material in solution, with functions for calculations
involving flow rate and concentration. A parent class to be used in
Variable_C_Stock and Variable_Q_Stock.
"""
def rpm(self, vol_per_rev, Q):
return (Q / vol_per_rev)
def T_stock(self, V_stock, Q_stock):
return (V_stock / Q_stock)
def M_stock(self, V_stock, C_stock):
return C_stock * V_stock
def V_super_stock(self, V_stock, C_stock, C_super_stock):
return V_stock * (C_stock / C_super_stock).to(u.dimensionless)
def dilution_factor(self, C_stock, C_super_stock):
return (C_stock / C_super_stock).to(u.dimensionless)
|
class Stock(object):
'''A stock of material in solution, with functions for calculations
involving flow rate and concentration. A parent class to be used in
Variable_C_Stock and Variable_Q_Stock.
'''
def rpm(self, vol_per_rev, Q):
pass
def T_stock(self, V_stock, Q_stock):
pass
def M_stock(self, V_stock, C_stock):
pass
def V_super_stock(self, V_stock, C_stock, C_super_stock):
pass
def dilution_factor(self, C_stock, C_super_stock):
pass
| 6 | 1 | 2 | 0 | 2 | 0 | 1 | 0.36 | 1 | 0 | 0 | 2 | 5 | 0 | 5 | 5 | 20 | 5 | 11 | 6 | 5 | 4 | 11 | 6 | 5 | 1 | 1 | 0 | 5 |
3,246 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/research/floc_model.py
|
aguaclara.research.floc_model.Material
|
class Material:
"""A particulate material with a name, diameter, density, and
molecular weight.
"""
def __init__(self, name, diameter, density, molecWeight):
"""Initialize a Material object.
:param name: Name of the material
:type name: string
:param diameter: Diameter of the material in particulate form
:type diameter: float
:param density: Density of the material (mass/volume)
:type density: float
:param molecWeight: Molecular weight of the material (mass/mole)
:type molecWeight: float
"""
self.name = name
self.Diameter = diameter
self.Density = density
self.MolecWeight = molecWeight
|
class Material:
'''A particulate material with a name, diameter, density, and
molecular weight.
'''
def __init__(self, name, diameter, density, molecWeight):
'''Initialize a Material object.
:param name: Name of the material
:type name: string
:param diameter: Diameter of the material in particulate form
:type diameter: float
:param density: Density of the material (mass/volume)
:type density: float
:param molecWeight: Molecular weight of the material (mass/mole)
:type molecWeight: float
'''
pass
| 2 | 2 | 16 | 1 | 5 | 10 | 1 | 2.17 | 0 | 0 | 0 | 1 | 1 | 4 | 1 | 1 | 21 | 2 | 6 | 6 | 4 | 13 | 6 | 6 | 4 | 1 | 0 | 0 | 1 |
3,247 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/research/floc_model.py
|
aguaclara.research.floc_model.Chemical
|
class Chemical(Material):
"""A chemical with a name, diameter, density, molecular weight, number of
aluminum atoms per molecule, and a precipitate.
"""
def __init__(self, name, diameter, density, molecWeight, Precipitate,
AluminumMPM=None):
"""Initialize a Chemical object.
:param name: Name of the material
:type name: string
:param diameter: Diameter of the material in particulate form
:type diameter: length
:param density: Density of the material
:type density: mass/length**3
:param molecWeight: Molecular weight of the material
:type molecWeight: mass/mole
:param Precipitate: Name of the precipitate
:type Precipitate: string
:param AluminumMPM: aluminum atoms per molecule
:type AluminumMPM: int
"""
Material.__init__(self, name, diameter, density, molecWeight)
self.AluminumMPM = AluminumMPM
self.Precip = Precipitate
if self.Precip == self.name:
self.PrecipName = name
self.PrecipDiameter = diameter
self.PrecipDensity = density
self.PrecipMolecWeight = molecWeight
self.PrecipAluminumMPM = AluminumMPM
else:
self.PrecipName = Precipitate
def define_Precip(self, diameter, density, molecweight, alumMPM):
"""Define a precipitate for the chemical.
:param diameter: Diameter of the precipitate in particulate form
:type diameter: float
:param density: Density of the material (mass/volume)
:type density: float
:param molecWeight: Molecular weight of the material (mass/mole)
:type molecWeight: float
:param alumMPM: aluminum atoms per molecule
:type alumMPM: int
"""
self.PrecipDiameter = diameter
self.PrecipDensity = density
self.PrecipMolecWeight = molecweight
self.PrecipAluminumMPM = alumMPM
|
class Chemical(Material):
'''A chemical with a name, diameter, density, molecular weight, number of
aluminum atoms per molecule, and a precipitate.
'''
def __init__(self, name, diameter, density, molecWeight, Precipitate,
AluminumMPM=None):
'''Initialize a Chemical object.
:param name: Name of the material
:type name: string
:param diameter: Diameter of the material in particulate form
:type diameter: length
:param density: Density of the material
:type density: mass/length**3
:param molecWeight: Molecular weight of the material
:type molecWeight: mass/mole
:param Precipitate: Name of the precipitate
:type Precipitate: string
:param AluminumMPM: aluminum atoms per molecule
:type AluminumMPM: int
'''
pass
def define_Precip(self, diameter, density, molecweight, alumMPM):
'''Define a precipitate for the chemical.
:param diameter: Diameter of the precipitate in particulate form
:type diameter: float
:param density: Density of the material (mass/volume)
:type density: float
:param molecWeight: Molecular weight of the material (mass/mole)
:type molecWeight: float
:param alumMPM: aluminum atoms per molecule
:type alumMPM: int
'''
pass
| 3 | 3 | 22 | 1 | 9 | 12 | 2 | 1.42 | 1 | 0 | 0 | 0 | 2 | 7 | 2 | 3 | 50 | 4 | 19 | 11 | 15 | 27 | 17 | 10 | 14 | 2 | 1 | 1 | 3 |
3,248 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/design/sed_tank.py
|
aguaclara.design.sed_tank.SedimentationTank
|
class SedimentationTank(Component):
"""Design an AguaClara plant's sedimentation tank.
An sedimentation tank's design relies on the sedimentation channel's design
in the same plant, but assumed/default values may be used to design an
sedimentation tank by itself. To design these components in tandem, use
:class:`aguaclara.design.sed.Sedimentor`.
Constants:
- ``INLET_MAN_Q_RATIO (float)``: The ratio of the flow in the inlet
manifold.
- ``OUTLET_MAN_HL (float * u.cm)``: The headloss of the outlet manifold
- ``JET_REVERSER_ND (float * u.inch)``: The nominal diameter of the jet
reverser.
- ``JET_PLANE_RATIO (float)``: The ratio for the jet plane
- ``JET_REVERSER_TO_DIFFUSERS_H (float * u.cm)``: The height between
the jet reverser and diffusers.
- ``WALL_THICKNESS (float * u.m)``: The thickness of the sed tank walls
- ``DIFFUSER_L (float * u.cm)``: The length of a diffuser.
Design Inputs:
- ``q (float * u.L / u.s)``: Plant flow rate
(recommended, defaults to 20L/s)
- ``temp (float * u.degC)``: Water temperature (recommended, defaults to
20°C)
- ``vel_upflow (float * u.mm / u.s)``: Upflow velocity
(optional, defaults to 1mm/s)
- ``l_inner (float * u.m)``: The inner length
(optional, defaults to 5.8m)
- ``w_inner (float * u.inch)``: The inner width
(optional, defaults to 42in.)
- ``diffuser_vel_max (float * u.cm / u.s)``: The max velocity of a
diffuser (optional, defaults to 44.29 cm/s)
- ``diffuser_n (int)``:The nunber of diffusers
(optional, defaults to 108)
- ``diffuser_wall_thickness (float * u.inch)``: The thickness of the
wall of a diffuser (optional, defaults to 1.17in.)
- ``diffuser_sdr (int)``: The standard dimension ratio of a diffuser
(optional, defaults to 41)
- ``inlet_man_hl (float * u.cm)``: The headloss of the inlet manifold
(optional, defaults to 1cm)
- ``inlet_man_sdr (float)``: The standard dimension ratio of the inlet
manifold (optional, defaults to 41)
- ``jet_reverser_sdr (int)``: The standard dimension ratio of the jet
reverser (optional, defaults to 26)
- ``plate_settler_angle (float * u.deg)``: The angle of the plate
settler (optional, defaults to 60°)
- ``plate_settler_s (float * u.cm)``: Spacing in between plate settlers
(optional, defaults to 2.5cm)
- ``plate_settler_thickness (float * u.mm)``: Thickness of a plate
settler (optional, defaults to 2mm)
- ``plate_settler_cantilever_l_max (float * u.cm)``: The max length of
the plate settler cantilever (optional, defaults to 20cm)
- ``plate_settler_vel_capture (float * u.mm / u.s)``: The capture
velocity of a plate settler (optional, defaults to 0.12mm/s)
- ``outlet_man_orifice_hl (float * u.cm)``: The headloss of the
orifices in the outlet manifold (optional, defaults to 4cm)
- ``outlet_man_orifice_q_ratio_max (float)``: The max ratio of the flow
rate for the orifices of the outlet manifold (optional, defaults to 0.8)
- ``outlet_man_orifice_n_est (int)``: The estimated number of orifices
for the outlet manifold (optional, defaults to 58)
- ``outlet_man_sdr (int)``: The standard dimension ratio of the outlet
manifold (optional, defaults to 41)
- ``slope_angle (float * u.deg)``: The angle at the bottom of the sed tank
(optional, defaults to 50°)
- ``side_slope_to_floc_weir_h_min (float * u.cm)``: The minimum height
between the side slope and the floc weir. (optional, defaults to 5cm)
- ``sed_chan_w_outer (float * u.cm)``: The outer width of the
sedimentation channel (optional, defaults to 60cm)
- ``sed_chan_weir_thickness (float * u.cm)``: The thickness of the
sedimentation channel weir (optional, defaults to 5cm)
- ``floc_weir_to_plate_frame_h (float * u.cm)``: The height from the
top of the floc weir to the plate settler frame (optional, defaults
to 10cm)
- ``hopper_slope_vertical_angle (float * u.deg)``: The angle of the
hopper wall slopes to vertical (optional, defaults to 60°)
"""
INLET_MAN_Q_RATIO = 0.8
OUTLET_MAN_HL = 4. * u.cm
JET_REVERSER_ND = 3. * u.inch
JET_PLANE_RATIO = 0.0124
JET_REVERSER_TO_DIFFUSERS_H = 3.0* u.cm
WALL_THICKNESS = 0.15 * u.m
DIFFUSER_L = 15.0 * u.cm
def __init__(self, **kwargs):
self.vel_upflow=1.0 * u.mm / u.s
self.l_inner=5.8 * u.m
self.w_inner=42.0 * u.inch
self.diffuser_vel_max=44.29 * u.cm / u.s
self.diffuser_n=108
self.diffuser_wall_thickness=1.17 * u.inch
self.diffuser_sdr=41
self.inlet_man_hl=1. * u.cm
self.inlet_man_sdr = 41
self.jet_reverser_sdr = 26
self.plate_settler_angle=60.0 * u.deg
self.plate_settler_s=2.5 * u.cm
self.plate_settler_thickness=2.0 * u.mm
self.plate_settler_cantilever_l_max=20.0 * u.cm
self.plate_settler_vel_capture=0.12 * u.mm / u.s
self.outlet_man_orifice_hl=4.0 * u.cm
self.outlet_man_orifice_q_ratio_max=0.8
self.outlet_man_orifice_n_est = 58
self.outlet_man_sdr=41
self.slope_angle=50. * u.deg
self.side_slope_to_floc_weir_h_min = 5.0 * u.cm
self.sed_chan_w_outer = 60.0 * u.cm
self.sed_chan_weir_thickness = 5.0 * u.cm
self.floc_weir_to_plate_frame_h = 10.0 * u.cm
self.hopper_slope_vertical_angle = 60.0 * u.deg
super().__init__(**kwargs)
@property
def q_tank(self):
"""The flow rate present in the tank."""
q_tank = self.l_inner * self.w_inner * self.vel_upflow
return q_tank.to(u.L / u.s)
@property
def diffuser_hl(self):
"""The headloss of the diffuser."""
return self.inlet_man_hl / self.diffuser_n
@property
def diffuser_vel(self):
"""The velocity of the diffuser"""
diffuser_vel = np.sqrt(2 * con.GRAVITY * self.diffuser_hl)
return diffuser_vel.to(u.mm / u.s)
@property
def diffuser_w_inner(self):
"""The inner width(neglecting walls) of the diffuser."""
diffuser_w_inner = self.w_inner * self.vel_upflow / self.diffuser_vel
return diffuser_w_inner.to(u.cm)
@property
def diffuser_a(self):
"""The area of the diffuser"""
diffuser_a = self.q_tank / (self.diffuser_vel * self.diffuser_n)
return diffuser_a.to(u.cm ** 2)
@property
def inlet_man_v_max(self):
"""The maximumum velocity in the inlet manifold."""
vel_manifold_max = np.sqrt(4 * con.GRAVITY * self.diffuser_hl *
(1 - self.INLET_MAN_Q_RATIO ** 2) /
(self.INLET_MAN_Q_RATIO ** 2 + 1)
)
return vel_manifold_max.to(u.m / u.s)
@property
def inlet_man_nd(self):
"""The nominal diameter of the inlet manifold"""
diam_inner = np.sqrt(4 * self.q_tank / (np.pi * self.inlet_man_v_max))
inlet_man_nd = pipe.ND_SDR_available(diam_inner, self.inlet_man_sdr)
return inlet_man_nd.to(u.cm)
@property
def outlet_man_nd(self):
"""The nominal diameter of the outlet manifold."""
outlet_man_nd = pc.manifold_nd(
self.q_tank,
self.OUTLET_MAN_HL,
self.l_inner,
self.outlet_man_orifice_q_ratio_max,
pc.viscosity_kinematic_water(self.temp),
mat.PVC_PIPE_ROUGH.to(u.m),
hl.PIPE_EXIT_K_MINOR,
self.outlet_man_orifice_n_est,
self.outlet_man_sdr
)
return outlet_man_nd
@property
def outlet_man_orifice_d(self):
"""The diameter of the orifices in the outlet manifold."""
Q_orifice = self.q_tank / self.outlet_man_orifice_n_est
D_orifice = pc.diam_circle(Q_orifice/(con.VC_ORIFICE_RATIO * \
np.sqrt(2 * con.GRAVITY* self.outlet_man_orifice_hl)))
return ut.ceil_nearest(D_orifice, drills.DRILL_BITS_D_METRIC)
@property
def plate_l(self):
"""The length of a plate in the plate settlers."""
L_sed_plate = ((self.plate_settler_s * ((self.vel_upflow / \
self.plate_settler_vel_capture) - 1)
+ self.plate_settler_thickness * (
self.vel_upflow / self.plate_settler_vel_capture))
/ (np.sin(self.plate_settler_angle) * \
np.cos(self.plate_settler_angle))
).to(u.m)
return L_sed_plate
@property
def outlet_man_orifice_q(self):
"""The flow rate in the orifices of the outlet manifold."""
outlet_man_orifice_q = pc.flow_orifice_vert(
self.outlet_man_orifice_d,
self.outlet_man_orifice_hl,
con.VC_ORIFICE_RATIO
)
return outlet_man_orifice_q.to(u.L / u.s)
@property
def outlet_man_orifice_spacing(self):
"""The spacing between orifices on the outlet manifold."""
outlet_man_orifice_spacing = (
self.l_inner -
pipe.socket_depth(self.outlet_man_nd) -
pipe.cap_thickness(self.outlet_man_nd) -
self.outlet_man_orifice_d
) / ((self.q_tank / self.outlet_man_orifice_q) - 1)
return outlet_man_orifice_spacing
@property
def outlet_man_orifice_n(self):
"""The number of orifices on the outlet manifold."""
outlet_orifice_n = math.floor(
(
self.l_inner -
pipe.socket_depth(self.outlet_man_nd) -
pipe.cap_thickness(self.outlet_man_nd) -
self.outlet_man_orifice_d
) / self.outlet_man_orifice_spacing
) + 1
return outlet_orifice_n
@property
def outlet_orifice_hl(self):
"""The headloss for the orifices of the outlet"""
outlet_orifice_hl = pc.head_orifice(
self.outlet_man_nd,
con.VC_ORIFICE_RATIO,
self.q_tank / self.outlet_man_orifice_n
)
return outlet_orifice_hl.to(u.mm)
@property
def side_slopes_w(self):
"""The width of the side slopes."""
side_slopes_w = (
self.w_inner -
pipe.ID_SDR(self.JET_REVERSER_ND, self.jet_reverser_sdr)
) / 2
return side_slopes_w.to(u.m)
@property
def side_slopes_h(self):
"""The height of the side slopes."""
side_slopes_h = np.tan(self.slope_angle) * self.side_slopes_w
return side_slopes_h.to(u.m)
@property
def inlet_man_h(self):
"""The height of the inlet manifold height."""
inlet_man_h = self.JET_REVERSER_TO_DIFFUSERS_H + self.DIFFUSER_L + \
( pipe.OD(self.inlet_man_nd)/ 2 )
return inlet_man_h
@property
def floc_weir_h(self):
"""The height of the floc weir."""
floc_weir_h = max(
self.inlet_man_h + (pipe.OD(self.inlet_man_nd) / 2) + \
mat.CONCRETE_THICKNESS_MIN,
self.side_slopes_h + self.side_slope_to_floc_weir_h_min
)
return floc_weir_h
|
class SedimentationTank(Component):
'''Design an AguaClara plant's sedimentation tank.
An sedimentation tank's design relies on the sedimentation channel's design
in the same plant, but assumed/default values may be used to design an
sedimentation tank by itself. To design these components in tandem, use
:class:`aguaclara.design.sed.Sedimentor`.
Constants:
- ``INLET_MAN_Q_RATIO (float)``: The ratio of the flow in the inlet
manifold.
- ``OUTLET_MAN_HL (float * u.cm)``: The headloss of the outlet manifold
- ``JET_REVERSER_ND (float * u.inch)``: The nominal diameter of the jet
reverser.
- ``JET_PLANE_RATIO (float)``: The ratio for the jet plane
- ``JET_REVERSER_TO_DIFFUSERS_H (float * u.cm)``: The height between
the jet reverser and diffusers.
- ``WALL_THICKNESS (float * u.m)``: The thickness of the sed tank walls
- ``DIFFUSER_L (float * u.cm)``: The length of a diffuser.
Design Inputs:
- ``q (float * u.L / u.s)``: Plant flow rate
(recommended, defaults to 20L/s)
- ``temp (float * u.degC)``: Water temperature (recommended, defaults to
20°C)
- ``vel_upflow (float * u.mm / u.s)``: Upflow velocity
(optional, defaults to 1mm/s)
- ``l_inner (float * u.m)``: The inner length
(optional, defaults to 5.8m)
- ``w_inner (float * u.inch)``: The inner width
(optional, defaults to 42in.)
- ``diffuser_vel_max (float * u.cm / u.s)``: The max velocity of a
diffuser (optional, defaults to 44.29 cm/s)
- ``diffuser_n (int)``:The nunber of diffusers
(optional, defaults to 108)
- ``diffuser_wall_thickness (float * u.inch)``: The thickness of the
wall of a diffuser (optional, defaults to 1.17in.)
- ``diffuser_sdr (int)``: The standard dimension ratio of a diffuser
(optional, defaults to 41)
- ``inlet_man_hl (float * u.cm)``: The headloss of the inlet manifold
(optional, defaults to 1cm)
- ``inlet_man_sdr (float)``: The standard dimension ratio of the inlet
manifold (optional, defaults to 41)
- ``jet_reverser_sdr (int)``: The standard dimension ratio of the jet
reverser (optional, defaults to 26)
- ``plate_settler_angle (float * u.deg)``: The angle of the plate
settler (optional, defaults to 60°)
- ``plate_settler_s (float * u.cm)``: Spacing in between plate settlers
(optional, defaults to 2.5cm)
- ``plate_settler_thickness (float * u.mm)``: Thickness of a plate
settler (optional, defaults to 2mm)
- ``plate_settler_cantilever_l_max (float * u.cm)``: The max length of
the plate settler cantilever (optional, defaults to 20cm)
- ``plate_settler_vel_capture (float * u.mm / u.s)``: The capture
velocity of a plate settler (optional, defaults to 0.12mm/s)
- ``outlet_man_orifice_hl (float * u.cm)``: The headloss of the
orifices in the outlet manifold (optional, defaults to 4cm)
- ``outlet_man_orifice_q_ratio_max (float)``: The max ratio of the flow
rate for the orifices of the outlet manifold (optional, defaults to 0.8)
- ``outlet_man_orifice_n_est (int)``: The estimated number of orifices
for the outlet manifold (optional, defaults to 58)
- ``outlet_man_sdr (int)``: The standard dimension ratio of the outlet
manifold (optional, defaults to 41)
- ``slope_angle (float * u.deg)``: The angle at the bottom of the sed tank
(optional, defaults to 50°)
- ``side_slope_to_floc_weir_h_min (float * u.cm)``: The minimum height
between the side slope and the floc weir. (optional, defaults to 5cm)
- ``sed_chan_w_outer (float * u.cm)``: The outer width of the
sedimentation channel (optional, defaults to 60cm)
- ``sed_chan_weir_thickness (float * u.cm)``: The thickness of the
sedimentation channel weir (optional, defaults to 5cm)
- ``floc_weir_to_plate_frame_h (float * u.cm)``: The height from the
top of the floc weir to the plate settler frame (optional, defaults
to 10cm)
- ``hopper_slope_vertical_angle (float * u.deg)``: The angle of the
hopper wall slopes to vertical (optional, defaults to 60°)
'''
def __init__(self, **kwargs):
pass
@property
def q_tank(self):
'''The flow rate present in the tank.'''
pass
@property
def diffuser_hl(self):
'''The headloss of the diffuser.'''
pass
@property
def diffuser_vel(self):
'''The velocity of the diffuser'''
pass
@property
def diffuser_w_inner(self):
'''The inner width(neglecting walls) of the diffuser.'''
pass
@property
def diffuser_a(self):
'''The area of the diffuser'''
pass
@property
def inlet_man_v_max(self):
'''The maximumum velocity in the inlet manifold.'''
pass
@property
def inlet_man_nd(self):
'''The nominal diameter of the inlet manifold'''
pass
@property
def outlet_man_nd(self):
'''The nominal diameter of the outlet manifold.'''
pass
@property
def outlet_man_orifice_d(self):
'''The diameter of the orifices in the outlet manifold.'''
pass
@property
def plate_l(self):
'''The length of a plate in the plate settlers.'''
pass
@property
def outlet_man_orifice_q(self):
'''The flow rate in the orifices of the outlet manifold.'''
pass
@property
def outlet_man_orifice_spacing(self):
'''The spacing between orifices on the outlet manifold.'''
pass
@property
def outlet_man_orifice_n(self):
'''The number of orifices on the outlet manifold.'''
pass
@property
def outlet_orifice_hl(self):
'''The headloss for the orifices of the outlet'''
pass
@property
def side_slopes_w(self):
'''The width of the side slopes.'''
pass
@property
def side_slopes_h(self):
'''The height of the side slopes.'''
pass
@property
def inlet_man_h(self):
'''The height of the inlet manifold height.'''
pass
@property
def floc_weir_h(self):
'''The height of the floc weir.'''
pass
| 38 | 19 | 8 | 0 | 7 | 1 | 1 | 0.58 | 1 | 1 | 0 | 0 | 19 | 25 | 19 | 46 | 276 | 29 | 156 | 89 | 118 | 91 | 90 | 71 | 70 | 1 | 5 | 0 | 19 |
3,249 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/design/sed_chan.py
|
aguaclara.design.sed_chan.SedimentationChannel
|
class SedimentationChannel(Component):
"""Design an AguaClara sedimentation channel.
The sedimentation channel relies on the number and dimensions of the
sedimentation tanks in the same plant, but assumed/default values may be
used to design a sedimentation channel by itself. To design these components
in tandem, use :class:`aguaclara.design.sed.Sedimentor`.
Constants:
- ``SED_TANK_Q_RATIO (float)``: Permissible ratio of influent flow
between the sedimentation tanks
- ``PLANT_FREE_BOARD_H (float * u.cm)``: Freeboard height in the plant
- ``WEIR_FREEBOARD_H (float * u.cm)``: Freeboard height of a channel
weir
- ``SED_DEPTH_EST (float * u.m)``: Estimated depth of the sedimentor
Design Inputs:
- ``q (float * u.L / u.s)``: Flow rate (recommended, defaults to 20L/s)
- ``temp (float * u.degC)``: Water temperature (recommended, defaults to
20°C)
- ``sed_tank_n (int)``: Number of sedimentation tanks (recommended,
defaults to 4)
- ``sed_tank_w_inner (float * u.inch)``: Inner width of the sedimentation
tank (recommended, defaults to 42 in)
- ``sed_tank_wall_thickness (float * u.cm)``: Wall thickness of the
sedimentation tank (recommended, defaults to 15 cm)
- ``sed_tank_inlet_man_nd (float * u.cm)``: Nominal diameter of the
sedimentation tank's inlet manifold (recommended, defaults to 60 cm)
- ``sed_tank_outlet_man_nd (float * u.cm)``: Nominal diameter of the
sedimentation tank's outlet manifold (recommended, defaults to 60 cm)
- ``sed_tank_outlet_man_hl (float * u.cm)``: Head loss in the
sedimentation tank's outlet manifold (recommended, defaults to 4 cm)
- ``sed_tank_diffuser_hl (float * u.mm)``: Head loss through a
diffuser in the sedimentation tank (recommended, defaults to 0.09 cm)
- ``sed_wall_thickness (float * u.cm)``: Wall thickness of the
sedimentor (recommended, defaults to 15 cm)
- ``weir_thickness (float * u.cm)``: Weir thickness (optional, defaults
to 15 cm)
- ``weir_hl (float * u.cm)``: Head loss over the weir (optional,
defaults to 5 cm)
- ``w_min (float * u.cm)``: Minimum width (optional, defaults to 30 cm)
- ``fitting_s (float * u.cm)``: Fitting spacing (optional, defaults
to 15 cm)
- ``inlet_depth_max (float * u.cm)``: Maximum inlet channel depth
(optional, defaults to 50 cm)
- ``drain_sdr (int)``: SDR of the drain pipe (optional, defaults to 26)
- ``outlet_free_h (float * u.cm)``: Permissible increase of water level
in the outlet channel (optional, defaults to 5 cm)
``outlet_weir_depth``:The depth of the outlet weir. (optional, defaults to 5 cm)
- ``outlet_pipe_sdr (int)``: SDR of the outlet pipe (optional, defaults
to 41)
- ``outlet_pipe_hl_max (float * u.cm)``: Maximum head loss through the
outlet pipe (optional, defaults to 1 cm)
- ``outlet_pipe_nd_max (float * u.inch)``: Maximum nominal diameter of
the outlet pipe (optional, defaults to 8 in)
"""
SED_TANK_Q_RATIO = 0.95
PLANT_FREEBOARD_H = 5.0 * u.cm
WEIR_FREEBOARD_H = 2.0 * u.cm
SED_DEPTH_EST = 2.0 * u.m
def __init__(self, **kwargs):
self.sed_tank_n=4
self.sed_tank_w_inner=42.0 * u.inch
self.sed_tank_wall_thickness = 15.0 * u.cm
self.sed_tank_inlet_man_nd = 60.0 * u.cm
self.sed_tank_outlet_man_nd = 60.0 * u.cm
self.sed_tank_outlet_man_hl = 4.0 * u.cm
self.sed_tank_diffuser_hl=0.09 * u.mm
self.sed_wall_thickness = 15.0 * u.cm
self.weir_thickness = 15.0 * u.cm
self.weir_hl = 5 * u.cm
self.w_min = 30.0 * u.cm
self.fitting_s = 15. * u.cm
self.inlet_depth_max = 50 * u.cm
self.drain_spec = 'sdr26'
self.outlet_free_h = 5.0 * u.cm
self.outlet_pipe_spec = 'sdr41'
self.outlet_pipe_hl_max = 1.0 * u.cm
self.outlet_pipe_nd_max = 8.0 * u.inch
self.drain_pipe = Pipe()
self.outlet_pipe = Pipe()
self.subcomponents = [self.drain_pipe, self.outlet_pipe]
super().__init__(**kwargs)
self._set_drain_pipe()
self._set_outlet_pipe()
super().set_subcomponents()
@property
def l(self):
"""Length of the sedimentation channel."""
l = (self.sed_tank_n * self.sed_tank_w_inner) + \
((self.sed_tank_n-1) * self.sed_tank_wall_thickness) + \
self.sed_wall_thickness
return l.to(u.m)
@property
def outlet_weir_hl(self):
"""Head loss over the outlet channel weir."""
weir_exit_hl = pc.headloss_weir_rect(self.q, self.l)
return weir_exit_hl
@property
def inlet_hl_max(self):
"""Maximum head loss in the inlet channel."""
inlet_hl_max = (self.sed_tank_outlet_man_hl + self.sed_tank_diffuser_hl) * \
(1 - self.SED_TANK_Q_RATIO ** 2)
return inlet_hl_max
@property
def _inlet_w_pre_weir_plumbing_min(self):
"""Minimum width of the inlet channel (pre-weir) to fit pipes."""
inlet_w_pre_weir_plumbing_min = pipe.fitting_od(self.sed_tank_inlet_man_nd) + \
2 * self.fitting_s
return inlet_w_pre_weir_plumbing_min
@property
def _inlet_w_pre_weir_hl_min(self):
"""Minimum width of the inlet channel (pre-weir) that doesn't exceed
the permissible head loss.
"""
inlet_w_pre_weir_hl_min = pc.horiz_chan_w(
self.q,
self.inlet_depth_max,
self.inlet_hl_max,
self.l,
pc.viscosity_kinematic_water(self.temp),
mat.CONCRETE_PIPE_ROUGH,
False,
0
)
return inlet_w_pre_weir_hl_min
@property
def inlet_w_pre_weir(self):
"""Width of the inlet channel (pre-weir)."""
inlet_w_pre_weir = max(
self._inlet_w_pre_weir_plumbing_min,
self._inlet_w_pre_weir_hl_min)
return inlet_w_pre_weir
@property
def _inlet_depth_plumbing_min(self):
"""Minimum depth of the inlet channel to fit pipes."""
inlet_plumbing_depth_min = self.sed_tank_outlet_man_hl + self.sed_tank_diffuser_hl + \
pipe.fitting_od(self.sed_tank_outlet_man_nd) + \
self.fitting_s + self.outlet_weir_hl
return inlet_plumbing_depth_min
@property
def _inlet_depth_hl_min(self):
"""Minimum depth of the inlet channel to stay within acceptable head
loss.
"""
inlet_chan_hl_depth = pc.horiz_chan_h(
self.q,
self.inlet_w_pre_weir,
self.inlet_hl_max,
self.l,
pc.viscosity_kinematic_water(self.temp),
mat.CONCRETE_PIPE_ROUGH,
False)
return inlet_chan_hl_depth
@property
def inlet_depth(self):
"""Depth of the inlet channel."""
inlet_depth = max(self._inlet_depth_plumbing_min, self._inlet_depth_hl_min)
return inlet_depth
@property
def inlet_weir_hl(self):
"""Head loss through the inlet channel weir."""
inlet_weir_hl = pc.headloss_weir_rect(self.q, self.l)
return inlet_weir_hl
@property
def inlet_h(self):
"""Height of the inlet channel."""
inlet_h = self.inlet_depth + self.PLANT_FREEBOARD_H
return inlet_h
@property
def inlet_weir_h(self):
"""Height of the inlet channel weir."""
inlet_chan_h_weir = self.inlet_depth + self.WEIR_FREEBOARD_H
return inlet_chan_h_weir
@property
def inlet_w_post_weir(self):
"""Width of the inlet channel (post-weir)"""
inlet_w_post_weir = max(
self.w_min,
pc.horiz_chan_w(
self.q,
self.inlet_h,
self.inlet_h,
self.l,
pc.viscosity_kinematic_water(self.temp),
mat.CONCRETE_PIPE_ROUGH,
1,
0 ))
return inlet_w_post_weir
@property
def inlet_w(self):
"""Width of the inlet channel"""
inlet_w = self.inlet_w_pre_weir + self.weir_thickness + self.inlet_w_post_weir
return inlet_w
def _set_drain_pipe(self):
drain_k_minor = hl.PIPE_ENTRANCE_K_MINOR + hl.PIPE_EXIT_K_MINOR + hl.EL90_K_MINOR
drain_nd = pc.pipe_flow_nd(
self.q,
ut.get_sdr(self.drain_spec),
self.SED_DEPTH_EST,
self.SED_DEPTH_EST + self.inlet_w,
pc.viscosity_kinematic_water(self.temp),
mat.PVC_PIPE_ROUGH,
drain_k_minor
)
self.drain_pipe = Pipe(
size = drain_nd,
spec = self.drain_spec,
k_minor = drain_k_minor,
)
@property
def inlet_drain_box_w(self):
"""Width of the inlet channel drain box"""
inlet_drain_box_w = max( 2 * self.fitting_s + pipe.fitting_od(self.drain_pipe.size), self.inlet_w_post_weir)
return inlet_drain_box_w
@property
def outlet_depth(self):
"""Depth of the outlet channel."""
outlet_depth = self.inlet_depth - self.sed_tank_outlet_man_hl - \
self.sed_tank_diffuser_hl
return outlet_depth
@property
def outlet_weir_depth(self):
"""Depth of the outlet channel weir."""
outlet_weir_depth = self.outlet_depth - self.weir_hl - self.WEIR_FREEBOARD_H
return outlet_weir_depth
@property
def outlet_w_pre_weir(self):
"""Width of the outlet channel (pre-weir)."""
return self.w_min
@property
def outlet_pipe_k_minor(self):
outlet_pipe_k_minor = 2 * hl.EL90_K_MINOR + hl.PIPE_ENTRANCE_K_MINOR + \
hl.PIPE_EXIT_K_MINOR
return outlet_pipe_k_minor
@property
def outlet_pipe_l(self):
outlet_pipe_l = ha.DRAIN_CHAN_WALKWAY_W + self.inlet_w + 1.0 * u.m
return outlet_pipe_l
@property
def outlet_pipe_q_max(self):
"""Maximum flow through the outlet pipe."""
outlet_pipe_q_max = pc.flow_pipe(
pipe.ID_SDR(self.outlet_pipe_nd_max, ut.get_sdr(self.outlet_pipe_spec)),
self.outlet_pipe_hl_max,
self.outlet_pipe_l,
pc.viscosity_kinematic_water(self.temp),
mat.PVC_PIPE_ROUGH,
self.outlet_pipe_k_minor
)
return ut.round_step(
outlet_pipe_q_max.to(u.L / u.s),
step = 0.0001 * u.L / u.s
)
def _set_outlet_pipe(self):
outlet_pipe_q = self.q / self.outlet_pipe_n
# outlet_pipe_nd = pc.pipe_flow_nd(
# outlet_pipe_q,
# ut.get_sdr(self.outlet_pipe_spec),
# self.outlet_pipe_hl_max,
# self.outlet_pipe_l,
# pc.viscosity_kinematic_water(self.temp),
# mat.PVC_PIPE_ROUGH,
# self.outlet_pipe_k_minor
# )
outlet_pipe_nd = pc.pipe_flow_nd(
outlet_pipe_q,
ut.get_sdr(self.outlet_pipe_spec),
self.outlet_pipe_hl_max,
self.outlet_pipe_l,
pc.viscosity_kinematic_water(self.temp),
mat.PVC_PIPE_ROUGH,
2 * hl.EL90_K_MINOR + hl.PIPE_ENTRANCE_K_MINOR + \
hl.PIPE_EXIT_K_MINOR
)
self.outlet_pipe = Pipe(
l = self.outlet_pipe_l,
q = outlet_pipe_q,
size = outlet_pipe_nd,
spec = self.outlet_pipe_spec,
k_minor = self.outlet_pipe_k_minor
)
@property
def outlet_pipe_n(self):
"""Number of outlet pipes."""
outlet_pipe_n = math.ceil(self.q / self.outlet_pipe_q_max)
return outlet_pipe_n
@property
def outlet_post_weir_w(self):
"""Width of the outlet channel (post-weir)."""
outlet_post_weir_w = max(
#need self.outlet_to_filter_nd
self.fitting_s + pipe.fitting_od(self.outlet_pipe.size),
self.fitting_s + pipe.fitting_od(self.drain_pipe.size),
self.w_min,
pc.horiz_chan_w(
self.q,
self.outlet_weir_depth - self.outlet_free_h, #what is outlet_free_h
self.outlet_weir_depth,
self.l,
pc.viscosity_kinematic_water(self.temp),
mat.PVC_PIPE_ROUGH,
1,
hl.PIPE_ENTRANCE_K_MINOR + hl.PIPE_EXIT_K_MINOR + hl.EL90_K_MINOR
)
)
return outlet_post_weir_w
@property
def outlet_w(self):
"""Width of the outlet channel."""
outlet_w = self.outlet_w_pre_weir + self.weir_thickness + \
self.outlet_post_weir_w
return outlet_w
@property
def outlet_drain_box_w(self):
"""Width of the outlet channel drain box."""
outlet_drain_box_w = max(
self.fitting_s + pipe.fitting_od(self.drain_pipe.size),
self.outlet_post_weir_w
)
return outlet_drain_box_w
@property
def outlet_weir_h(self):
"""Height of the outlet channel weir."""
outlet_weir_h = self.outlet_weir_depth + self.WEIR_FREEBOARD_H
return outlet_weir_h
@property
def w_outer(self):
"""Outer width of the sedimentation channel."""
w_outer = self.outlet_w + 2 * self.weir_thickness + self.inlet_w + self.sed_wall_thickness
return w_outer
@property
def inlet_last_coupling_h(self):
"""Height of the last coupling in the inlet channel."""
last_coupling_h = self.outlet_weir_depth - 2 * u.cm
return last_coupling_h
@property
def inlet_step_h(self):
"""Height of the steps between each pipe in the inlet channel."""
step_h = self.inlet_last_coupling_h / max(1, self.sed_tank_n - 1)
return step_h
@property
def inlet_slope_l(self):
"""Length of the slopes between each pipe in the inlet channel."""
inlet_slope_l = self.l + self.sed_wall_thickness - \
pipe.fitting_od(self.sed_tank_inlet_man_nd) - self.fitting_s
return inlet_slope_l
|
class SedimentationChannel(Component):
'''Design an AguaClara sedimentation channel.
The sedimentation channel relies on the number and dimensions of the
sedimentation tanks in the same plant, but assumed/default values may be
used to design a sedimentation channel by itself. To design these components
in tandem, use :class:`aguaclara.design.sed.Sedimentor`.
Constants:
- ``SED_TANK_Q_RATIO (float)``: Permissible ratio of influent flow
between the sedimentation tanks
- ``PLANT_FREE_BOARD_H (float * u.cm)``: Freeboard height in the plant
- ``WEIR_FREEBOARD_H (float * u.cm)``: Freeboard height of a channel
weir
- ``SED_DEPTH_EST (float * u.m)``: Estimated depth of the sedimentor
Design Inputs:
- ``q (float * u.L / u.s)``: Flow rate (recommended, defaults to 20L/s)
- ``temp (float * u.degC)``: Water temperature (recommended, defaults to
20°C)
- ``sed_tank_n (int)``: Number of sedimentation tanks (recommended,
defaults to 4)
- ``sed_tank_w_inner (float * u.inch)``: Inner width of the sedimentation
tank (recommended, defaults to 42 in)
- ``sed_tank_wall_thickness (float * u.cm)``: Wall thickness of the
sedimentation tank (recommended, defaults to 15 cm)
- ``sed_tank_inlet_man_nd (float * u.cm)``: Nominal diameter of the
sedimentation tank's inlet manifold (recommended, defaults to 60 cm)
- ``sed_tank_outlet_man_nd (float * u.cm)``: Nominal diameter of the
sedimentation tank's outlet manifold (recommended, defaults to 60 cm)
- ``sed_tank_outlet_man_hl (float * u.cm)``: Head loss in the
sedimentation tank's outlet manifold (recommended, defaults to 4 cm)
- ``sed_tank_diffuser_hl (float * u.mm)``: Head loss through a
diffuser in the sedimentation tank (recommended, defaults to 0.09 cm)
- ``sed_wall_thickness (float * u.cm)``: Wall thickness of the
sedimentor (recommended, defaults to 15 cm)
- ``weir_thickness (float * u.cm)``: Weir thickness (optional, defaults
to 15 cm)
- ``weir_hl (float * u.cm)``: Head loss over the weir (optional,
defaults to 5 cm)
- ``w_min (float * u.cm)``: Minimum width (optional, defaults to 30 cm)
- ``fitting_s (float * u.cm)``: Fitting spacing (optional, defaults
to 15 cm)
- ``inlet_depth_max (float * u.cm)``: Maximum inlet channel depth
(optional, defaults to 50 cm)
- ``drain_sdr (int)``: SDR of the drain pipe (optional, defaults to 26)
- ``outlet_free_h (float * u.cm)``: Permissible increase of water level
in the outlet channel (optional, defaults to 5 cm)
``outlet_weir_depth``:The depth of the outlet weir. (optional, defaults to 5 cm)
- ``outlet_pipe_sdr (int)``: SDR of the outlet pipe (optional, defaults
to 41)
- ``outlet_pipe_hl_max (float * u.cm)``: Maximum head loss through the
outlet pipe (optional, defaults to 1 cm)
- ``outlet_pipe_nd_max (float * u.inch)``: Maximum nominal diameter of
the outlet pipe (optional, defaults to 8 in)
'''
def __init__(self, **kwargs):
pass
@property
def l(self):
'''Length of the sedimentation channel.'''
pass
@property
def outlet_weir_hl(self):
'''Head loss over the outlet channel weir.'''
pass
@property
def inlet_hl_max(self):
'''Maximum head loss in the inlet channel.'''
pass
@property
def _inlet_w_pre_weir_plumbing_min(self):
'''Minimum width of the inlet channel (pre-weir) to fit pipes.'''
pass
@property
def _inlet_w_pre_weir_hl_min(self):
'''Minimum width of the inlet channel (pre-weir) that doesn't exceed
the permissible head loss.
'''
pass
@property
def inlet_w_pre_weir(self):
'''Width of the inlet channel (pre-weir).'''
pass
@property
def _inlet_depth_plumbing_min(self):
'''Minimum depth of the inlet channel to fit pipes.'''
pass
@property
def _inlet_depth_hl_min(self):
'''Minimum depth of the inlet channel to stay within acceptable head
loss.
'''
pass
@property
def inlet_depth(self):
'''Depth of the inlet channel.'''
pass
@property
def inlet_weir_hl(self):
'''Head loss through the inlet channel weir.'''
pass
@property
def inlet_hl_max(self):
'''Height of the inlet channel.'''
pass
@property
def inlet_weir_hl(self):
'''Height of the inlet channel weir.'''
pass
@property
def inlet_w_post_weir(self):
'''Width of the inlet channel (post-weir)'''
pass
@property
def inlet_w_pre_weir(self):
'''Width of the inlet channel'''
pass
def _set_drain_pipe(self):
pass
@property
def inlet_drain_box_w(self):
'''Width of the inlet channel drain box'''
pass
@property
def outlet_depth(self):
'''Depth of the outlet channel.'''
pass
@property
def outlet_weir_depth(self):
'''Depth of the outlet channel weir.'''
pass
@property
def outlet_w_pre_weir(self):
'''Width of the outlet channel (pre-weir).'''
pass
@property
def outlet_pipe_k_minor(self):
pass
@property
def outlet_pipe_l(self):
pass
@property
def outlet_pipe_q_max(self):
'''Maximum flow through the outlet pipe.'''
pass
def _set_outlet_pipe(self):
pass
@property
def outlet_pipe_n(self):
'''Number of outlet pipes.'''
pass
@property
def outlet_post_weir_w(self):
'''Width of the outlet channel (post-weir).'''
pass
@property
def outlet_weir_hl(self):
'''Width of the outlet channel.'''
pass
@property
def outlet_drain_box_w(self):
'''Width of the outlet channel drain box.'''
pass
@property
def outlet_weir_hl(self):
'''Height of the outlet channel weir.'''
pass
@property
def w_outer(self):
'''Outer width of the sedimentation channel.'''
pass
@property
def inlet_last_coupling_h(self):
'''Height of the last coupling in the inlet channel.'''
pass
@property
def inlet_step_h(self):
'''Height of the steps between each pipe in the inlet channel.'''
pass
@property
def inlet_slope_l(self):
'''Length of the slopes between each pipe in the inlet channel.'''
pass
| 64 | 29 | 8 | 0 | 7 | 1 | 1 | 0.38 | 1 | 2 | 1 | 0 | 33 | 21 | 33 | 60 | 387 | 43 | 250 | 122 | 186 | 95 | 128 | 92 | 94 | 1 | 5 | 0 | 33 |
3,250 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/design/sed.py
|
aguaclara.design.sed.Sedimentor
|
class Sedimentor(Component):
"""Design an AguaClara sedimentor.
The ``Sedimentor`` class designs the sedimentation tank and channel in
tandem. For more information on those classes, see
:class:`aguaclara.design.sed_tank.SedimentationTank` and
:class:`aguaclara.design.sed_chan.SedimentationChannel`.
Design inputs:
- ``q (float * u.L / u.s)``: Flow rate (recommended, defaults to 20L/s)
- ``temp (float * u.degC)``: Water temperature (recommended, defaults to
20°C)
- ``wall_thickness (float * u.cm)``: Wall thickness (optional, defaults
to 15 * u.cm)
- ``tank (SedimentationTank)``: Sedimentation Tank
(optional, see :class:`aguaclara.design.sed_tank.SedimentationTank`
for defaults)
- ``chan (SedimentationChannel)``: Sedimentation Channel
(optional, see
:class:`aguaclara.design.sed_chan.SedimentationChannel` for defaults)
"""
def __init__(self, **kwargs):
self.wall_thickness = 15.0 * u.cm
self.tank = SedimentationTank()
self.chan = SedimentationChannel()
self.subcomponents = [self.tank, self.chan]
super().__init__(**kwargs)
super().set_subcomponents()
self._design_chan()
self._design_tank()
@property
def tank_n(self):
"""The number of sedimentation tanks."""
tank_n = np.ceil(self.q / self.tank.q_tank)
return int(tank_n)
def _design_chan(self):
"""Design the sedimentation channel based off of the tank."""
self.chan.sed_tank_n = self.tank_n
self.chan.sed_tank_diffuser_hl = self.tank.diffuser_hl
self.chan.sed_tank_inlet_man_nd = self.tank.inlet_man_nd
self.chan.sed_tank_outlet_man_nd = self.tank.outlet_man_nd
self.chan.sed_tank_outlet_man_hl = self.tank.outlet_man_orifice_hl
self.chan.sed_tank_diffuser_hl = self.tank.diffuser_hl
self.chan.w_inner = self.tank.w_inner
self.chan.sed_tank_wall_thickness = self.tank.WALL_THICKNESS
self.chan.sed_wall_thickness = self.wall_thickness
def _design_tank(self):
"""Design the sedimentation tank based off of the channel"""
self.tank.sed_chan_w_outer = self.chan.w_outer
self.tank.sed_chan_weir_thickness = self.chan.weir_thickness
|
class Sedimentor(Component):
'''Design an AguaClara sedimentor.
The ``Sedimentor`` class designs the sedimentation tank and channel in
tandem. For more information on those classes, see
:class:`aguaclara.design.sed_tank.SedimentationTank` and
:class:`aguaclara.design.sed_chan.SedimentationChannel`.
Design inputs:
- ``q (float * u.L / u.s)``: Flow rate (recommended, defaults to 20L/s)
- ``temp (float * u.degC)``: Water temperature (recommended, defaults to
20°C)
- ``wall_thickness (float * u.cm)``: Wall thickness (optional, defaults
to 15 * u.cm)
- ``tank (SedimentationTank)``: Sedimentation Tank
(optional, see :class:`aguaclara.design.sed_tank.SedimentationTank`
for defaults)
- ``chan (SedimentationChannel)``: Sedimentation Channel
(optional, see
:class:`aguaclara.design.sed_chan.SedimentationChannel` for defaults)
'''
def __init__(self, **kwargs):
pass
@property
def tank_n(self):
'''The number of sedimentation tanks.'''
pass
def _design_chan(self):
'''Design the sedimentation channel based off of the tank.'''
pass
def _design_tank(self):
'''Design the sedimentation tank based off of the channel'''
pass
| 6 | 4 | 8 | 1 | 6 | 1 | 1 | 0.78 | 1 | 4 | 2 | 0 | 4 | 4 | 4 | 31 | 56 | 8 | 27 | 11 | 21 | 21 | 26 | 10 | 21 | 1 | 5 | 0 | 4 |
3,251 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/design/plant.py
|
aguaclara.design.plant.Plant
|
class Plant(Component):
"""Functions for designing an AguaClara water treatment plant."""
def __init__(self, **kwargs):
self.etf = EntTankFloc()
self.sed = Sedimentor()
self.subcomponents = [self.etf, self.sed]
super().__init__(**kwargs)
super().set_subcomponents()
self.design_floc()
def design_floc(self):
self.etf.floc.sed_chan_inlet_w_pre_weir = self.sed.chan.inlet_w_pre_weir
|
class Plant(Component):
'''Functions for designing an AguaClara water treatment plant.'''
def __init__(self, **kwargs):
pass
def design_floc(self):
pass
| 3 | 1 | 6 | 1 | 5 | 0 | 1 | 0.1 | 1 | 3 | 2 | 0 | 2 | 3 | 2 | 29 | 14 | 3 | 10 | 6 | 7 | 1 | 10 | 6 | 7 | 1 | 5 | 0 | 2 |
3,252 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/design/pipeline.py
|
aguaclara.design.pipeline.Tee
|
class Tee(PipelineComponent):
"""Design class for a Tee
Instantiate this class to create a readily constructible tee fitting and
calculate its hydraulic features.
``Tee``'s may be instantiated from a nominal size (to fit into an existing
pipeline) or inner diameter (to follow hydraulic constraints), but not both.
Constants:
- ``AVAILABLE_PATHS (str list)``: The available paths for the left and
right outlet. Branch meaning the flow would turn, run meaning the flow
stays straight, and stopper meaning there is no flow for that outlet
due to a stopper.
Design Inputs:
- ``q (float * u.L / u.s)``: Flow rate (recommended, defaults to 20L/s)
- ``temp (float * u.degC)``: Water temperature
(recommended, defaults to 20°C )
- ``size (float * u.inch)``: The size (recommended, defaults to 0.5 in.)
- ``fluid_type (str)``: The type of fluid flowing inside
(optional, defaults to water)
- ``left (PipelineComponent)``: The type of piping for the left outlet,
cannot be an elbow or tee (recommended, defaults to None)
- ``left_type (str)``: The type of path for the left outlet,
can only be one of the elements in AVAILABLE_PATHS.
can only be one of the elements in AVAILABLE_PATHS.
can only be one of the elements in AVAILABLE_PATHS.
(recommended, defaults to 'branch')
- ``right (PipelineComponent)``: The type of piping for the right outlet,
cannot be an elbow or tee. (recommended, defaults to None)
- ``right_type (str)``: The type of path for the right outlet,
can only be one of the elements in AVAILABLE_PATHS.
can only be one of the elements in AVAILABLE_PATHS.
can only be one of the elements in AVAILABLE_PATHS.
(recommended, defaults to 'stopper')
- ``id (float * u.inch)``: The inner diameter.
(recommended, defaults to 0.848 * u.inch)
"""
AVAILABLE_PATHS = ['branch', 'run', 'stopper']
def __init__(self, **kwargs):
self.left = None
self.left_type = 'branch'
self.right = None
self.right_type = 'stopper'
self.id = 0.848 * u.inch
super().__init__(**kwargs)
self._set_k_minor()
self._set_next()
if 'size' in kwargs:
self.id = self._get_id(self.size)
elif 'id' in kwargs:
self.size = self._get_size(self.id)
self._rep_ok()
def _set_k_minor(self):
"""Sets k minor for the left and right outlet"""
if self.left_type == 'branch':
self.left_k_minor = hl.TEE_FLOW_BR_K_MINOR
elif self.left_type == 'run':
self.left_k_minor = hl.TEE_FLOW_RUN_K_MINOR
elif self.left_type == 'stopper':
self.left_k_minor = None
if self.right_type == 'branch':
self.right_k_minor = hl.TEE_FLOW_BR_K_MINOR
elif self.right_type == 'run':
self.right_k_minor = hl.TEE_FLOW_RUN_K_MINOR
elif self.right_type == 'stopper':
self.right_k_minor = None
def _set_next(self):
"""Sets the next outlet as well the the type of branch for the next
outlet.
"""
if self.left_type == 'stopper':
self.next = self.right
self.next_type = self.right_type
else:
self.next = self.left
self.next_type = self.left_type
def _headloss_left(self):
"""The headloss of the left outlet"""
return pc.headloss_minor_elbow(self.q, self.id, self.left_k_minor).to(u.cm)
def _headloss_right(self):
"""The headloss of the right outlet"""
return pc.headloss_minor_elbow(self.q, self.id, self.right_k_minor).to(u.cm)
@property
def headloss(self):
"""The headloss"""
if self.left_type =='stopper':
return self._headloss_right()
else:
return self._headloss_left()
def _get_size(self, id_):
"""Get the nominal size based off the inner diameter
Args:
- ``id_ (float * u.inch)``: Inner diameter
"""
myindex = (np.abs(AVAILABLE_FITTING_IDS - id_)).argmin()
self.id = AVAILABLE_FITTING_IDS[myindex]
return AVAILABLE_FITTING_SIZES[myindex]
def _get_id(self, size):
"""Get the inner diameter based off the size.
Args:
- ``size (float * u.inch)``: Nominal size
"""
myindex = (np.abs(AVAILABLE_FITTING_SIZES - size)).argmin()
self.size = AVAILABLE_FITTING_SIZES[myindex]
return AVAILABLE_FITTING_IDS[myindex]
def format_print(self):
"""The string representation of this tee."""
return 'Tee: (Size: {}, ID: {}, Next Path Type: {})'.format(
self.size, self.id, self.next_type)
def _rep_ok(self):
"""Verify that this representation of a Tee is valid."""
if [self.left_type, self.right_type].count('stopper') != 1:
raise ValueError('All tees must have one stopper.')
if self.left_type not in self.AVAILABLE_PATHS:
raise ValueError(
'type of branch for left outlet must be in ',
self.AVAILABLE_PATHS)
if self.right_type not in self.AVAILABLE_PATHS:
raise ValueError(
'type of branch for right outlet must be in ',
self.AVAILABLE_PATHS)
if self.next is not None and self.size != self.next.size:
raise ValueError('The next component doesn\'t have the same size.')
if self.next is not None and type(self.next) in [Elbow, Tee]:
raise ValueError('Tees cannot be followed by other fittings.')
|
class Tee(PipelineComponent):
'''Design class for a Tee
Instantiate this class to create a readily constructible tee fitting and
calculate its hydraulic features.
``Tee``'s may be instantiated from a nominal size (to fit into an existing
pipeline) or inner diameter (to follow hydraulic constraints), but not both.
Constants:
- ``AVAILABLE_PATHS (str list)``: The available paths for the left and
right outlet. Branch meaning the flow would turn, run meaning the flow
stays straight, and stopper meaning there is no flow for that outlet
due to a stopper.
Design Inputs:
- ``q (float * u.L / u.s)``: Flow rate (recommended, defaults to 20L/s)
- ``temp (float * u.degC)``: Water temperature
(recommended, defaults to 20°C )
- ``size (float * u.inch)``: The size (recommended, defaults to 0.5 in.)
- ``fluid_type (str)``: The type of fluid flowing inside
(optional, defaults to water)
- ``left (PipelineComponent)``: The type of piping for the left outlet,
cannot be an elbow or tee (recommended, defaults to None)
- ``left_type (str)``: The type of path for the left outlet,
can only be one of the elements in AVAILABLE_PATHS.
can only be one of the elements in AVAILABLE_PATHS.
can only be one of the elements in AVAILABLE_PATHS.
(recommended, defaults to 'branch')
- ``right (PipelineComponent)``: The type of piping for the right outlet,
cannot be an elbow or tee. (recommended, defaults to None)
- ``right_type (str)``: The type of path for the right outlet,
can only be one of the elements in AVAILABLE_PATHS.
can only be one of the elements in AVAILABLE_PATHS.
can only be one of the elements in AVAILABLE_PATHS.
(recommended, defaults to 'stopper')
- ``id (float * u.inch)``: The inner diameter.
(recommended, defaults to 0.848 * u.inch)
'''
def __init__(self, **kwargs):
pass
def _set_k_minor(self):
'''Sets k minor for the left and right outlet'''
pass
def _set_next(self):
'''Sets the next outlet as well the the type of branch for the next
outlet.
'''
pass
def _headloss_left(self):
'''The headloss of the left outlet'''
pass
def _headloss_right(self):
'''The headloss of the right outlet'''
pass
@property
def headloss(self):
'''The headloss'''
pass
def _get_size(self, id_):
'''Get the nominal size based off the inner diameter
Args:
- ``id_ (float * u.inch)``: Inner diameter
'''
pass
def _get_id(self, size):
'''Get the inner diameter based off the size.
Args:
- ``size (float * u.inch)``: Nominal size
'''
pass
def format_print(self):
'''The string representation of this tee.'''
pass
def _rep_ok(self):
'''Verify that this representation of a Tee is valid.'''
pass
| 12 | 10 | 10 | 1 | 7 | 2 | 3 | 0.71 | 1 | 3 | 1 | 0 | 10 | 10 | 10 | 49 | 151 | 28 | 72 | 25 | 60 | 51 | 59 | 24 | 48 | 7 | 6 | 1 | 25 |
3,253 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/design/pipeline.py
|
aguaclara.design.pipeline.Pipe
|
class Pipe(PipelineComponent):
"""Design class for a pipe
Instantiate this class to create a readily constructible pipe and calculate
its hydraulic features.
``Pipe``'s may be instantiated from a nominal size (to fit into an existing
pipeline) or inner diameter (to follow hydraulic constraints), but not both.
Design Inputs:
- ``q (float * u.L/u.s)``: Flow rate (recommended, defaults to 20 L/s)
- ``temp (float * u.degC)``: Water temperature (recommended, defaults to
20°C)
- ``size (float * u.inch)``: Nominal size (recommended, defaults to 0.5
in)
- ``fluid_type (str)``: Fluid type. Must be 'water', 'pacl', or 'alum'
(optional, defaults to 'water')
- ``next (PipelineComponent)``: The next pipeline component with respect
to the flow direction. This can be either a newly-instantiated
``PipelineComponent`` child class, or a variable that contains such
a component (optional, defaults to None)
- ``id (float * u.inch)``: Inner diameter (optional, defaults to 0.476
in)
- ``spec (str)``: The pipe specification. Must be one of 'sdr26',
'sdr41', or 'sch40'. (optional, defaults to 'sdr41')
- ``l (float * u.m)``: Length of the pipe (optional, defaults to
1 m)
- ``pipe_rough (float * u.mm)``: Pipe roughness (optional, defaults to
PVC pipe roughness of 12 mm)
- ``k_minor (float)``: The minor loss coefficient (k-value) (optional,
defaults to 0)
"""
AVAILABLE_SPECS = ['sdr26', 'sdr41', 'sch40']
def __init__(self, **kwargs):
self.id = 0.476 * u.inch
self.spec = 'sdr41'
self.l = 1 * u.m
self.pipe_rough = mats.PVC_PIPE_ROUGH
super().__init__(**kwargs)
if 'size' in kwargs:
self.id = self._get_id(self.size, self.spec)
elif 'id' in kwargs:
self.size = self._get_size(self.id, self.spec)
self._rep_ok()
@property
def od(self):
"""The outer diameter of the pipe"""
index = (
np.abs(np.array(_pipe_database['NDinch']) - self.size.magnitude)
).argmin()
return _pipe_database.iloc[index, 1] * u.inch
def _get_size(self, id_, spec):
"""Get the size of a pipe given an inner diameter and specification.
Args:
- ``id_ (float * u.inch)``: Inner diameter
- ``spec (str)``: Pipe specification
"""
if spec[:3] == 'sdr':
return self._get_size_sdr(id_, int(spec[3:]))
elif spec == 'sch40':
return self._get_size_sch40(id_)
def _get_id(self, size, spec):
"""Get the inner diameter of a pipe given the size and specification.
Args:
- ``size (float * u.inch)``: Nominal size
- ``spec (str)``: Pipe specifcation
"""
if spec[:3] == 'sdr':
return self._get_id_sdr(size, int(spec[3:]))
elif spec == 'sch40':
return self._get_id_sch40(size)
def _get_id_sdr(self, size, sdr):
"""Get the inner diameter of a pipe given the size and SDR.
Args:
- ``size (float * u.inch)``: Nominal size
- ``sdr (int)``: Standard dimension ratio
"""
self.size = super()._get_available_size(size)
return self.size * (sdr - 2) / sdr
def _get_id_sch40(self, size):
"""Get the inner diameter of a SCH40 pipe.
Args:
- ``size (float * u.inch)``: Nominal size
"""
self.size = super().get_available_size(size)
myindex = (np.abs(AVAILABLE_SIZES - self.size)).argmin()
return AVAILABLE_IDS_SCH40[myindex]
def _get_size_sdr(self, id_, sdr):
"""Get the size of an SDR pipe.
Args:
- ``id_ (float * u.inch)``: Inner diameter
- ``sdr (int)``: Standard dimension ratio
"""
nd = super()._get_available_size((id_ * sdr) / (sdr - 2))
self.id = self._get_id_sdr(nd, sdr)
return nd
def _get_size_sch40(self, id_):
"""Get the size of a SCH40 pipe.
Args:
- ``id_ (float * u.inch)``: Inner diameter
"""
myindex = (np.abs(AVAILABLE_IDS_SCH40 - id_)).argmin()
self.id = AVAILABLE_IDS_SCH40[myindex]
return AVAILABLE_SIZES[myindex]
def ID_SDR_all_available(self, SDR):
"""Return an array of inner diameters with a given SDR."""
ID = []
for i in range(len(AVAILABLE_SIZES)):
ID.append(self._get_id_sdr(AVAILABLE_SIZES[i], SDR).magnitude)
return ID * u.inch
@property
def headloss(self):
"""Return the total head loss from major and minor losses in a pipe."""
return pc.headloss_major_pipe(
self.q, self.id, self.l, self.nu, self.pipe_rough
).to(u.cm)
def format_print(self):
"""Return the string representation of this pipe."""
return 'Pipe: (OD: {}, Size: {}, ID: {}, Length: {}, Spec: {})'.format(
self.od, self.size, self.id, self.l, self.spec)
def _rep_ok(self):
"""Verify that this representation of a Pipe is valid."""
if self.spec not in self.AVAILABLE_SPECS:
raise AttributeError('spec must be one of:', self.AVAILABLE_SPECS)
if self.next is not None and self.size != self.next.size:
raise ValueError('size of the next pipeline component must be the '
'same size as the current pipeline component')
|
class Pipe(PipelineComponent):
'''Design class for a pipe
Instantiate this class to create a readily constructible pipe and calculate
its hydraulic features.
``Pipe``'s may be instantiated from a nominal size (to fit into an existing
pipeline) or inner diameter (to follow hydraulic constraints), but not both.
Design Inputs:
- ``q (float * u.L/u.s)``: Flow rate (recommended, defaults to 20 L/s)
- ``temp (float * u.degC)``: Water temperature (recommended, defaults to
20°C)
- ``size (float * u.inch)``: Nominal size (recommended, defaults to 0.5
in)
- ``fluid_type (str)``: Fluid type. Must be 'water', 'pacl', or 'alum'
(optional, defaults to 'water')
- ``next (PipelineComponent)``: The next pipeline component with respect
to the flow direction. This can be either a newly-instantiated
``PipelineComponent`` child class, or a variable that contains such
a component (optional, defaults to None)
- ``id (float * u.inch)``: Inner diameter (optional, defaults to 0.476
in)
- ``spec (str)``: The pipe specification. Must be one of 'sdr26',
'sdr41', or 'sch40'. (optional, defaults to 'sdr41')
- ``l (float * u.m)``: Length of the pipe (optional, defaults to
1 m)
- ``pipe_rough (float * u.mm)``: Pipe roughness (optional, defaults to
PVC pipe roughness of 12 mm)
- ``k_minor (float)``: The minor loss coefficient (k-value) (optional,
defaults to 0)
'''
def __init__(self, **kwargs):
pass
@property
def od(self):
'''The outer diameter of the pipe'''
pass
def _get_size(self, id_, spec):
'''Get the size of a pipe given an inner diameter and specification.
Args:
- ``id_ (float * u.inch)``: Inner diameter
- ``spec (str)``: Pipe specification
'''
pass
def _get_id(self, size, spec):
'''Get the inner diameter of a pipe given the size and specification.
Args:
- ``size (float * u.inch)``: Nominal size
- ``spec (str)``: Pipe specifcation
'''
pass
def _get_id_sdr(self, size, sdr):
'''Get the inner diameter of a pipe given the size and SDR.
Args:
- ``size (float * u.inch)``: Nominal size
- ``sdr (int)``: Standard dimension ratio
'''
pass
def _get_id_sch40(self, size):
'''Get the inner diameter of a SCH40 pipe.
Args:
- ``size (float * u.inch)``: Nominal size
'''
pass
def _get_size_sdr(self, id_, sdr):
'''Get the size of an SDR pipe.
Args:
- ``id_ (float * u.inch)``: Inner diameter
- ``sdr (int)``: Standard dimension ratio
'''
pass
def _get_size_sch40(self, id_):
'''Get the size of a SCH40 pipe.
Args:
- ``id_ (float * u.inch)``: Inner diameter
'''
pass
def ID_SDR_all_available(self, SDR):
'''Return an array of inner diameters with a given SDR.'''
pass
@property
def headloss(self):
'''Return the total head loss from major and minor losses in a pipe.'''
pass
def format_print(self):
'''Return the string representation of this pipe.'''
pass
def _rep_ok(self):
'''Verify that this representation of a Pipe is valid.'''
pass
| 15 | 12 | 9 | 1 | 5 | 3 | 2 | 0.97 | 1 | 5 | 0 | 0 | 12 | 5 | 12 | 51 | 149 | 25 | 63 | 27 | 48 | 61 | 52 | 25 | 39 | 3 | 6 | 1 | 21 |
3,254 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/design/pipeline.py
|
aguaclara.design.pipeline.Elbow
|
class Elbow(PipelineComponent):
"""Design class for an Elbow
Instantiate this class to create a readily constructible Elbow fitting and
calculate its hydraulic features.
``Elbow``'s may be instantiated from a nominal size (to fit into an existing
pipeline) or inner diameter (to follow hydraulic constraints), but not both.
Constants:
- ``AVAILABLE_ANGLES (int * u.deg list)``: The possible angles for this
fitting.
Design Inputs:
- ``q (float * u.L/u.s)``: Flow rate (recommended, defaults to 20L/s)
- ``temp (float * u.degC)``: Water temperature
(recommended, defaults to 20°C)
- ``size (float * u.inch)``: The nominal size
(recommended, defaults to 0.5 in.)
- ``fluid_type (str)``: Fluid type. Must be 'water', 'pacl', or 'alum'
(optional, defaults to 'water')
- ``next (PipelineComponent)``: The next pipeline component after the
outlet, cannot be another Elbow or a Tee fitting.
outlet, cannot be another Elbow or a Tee fitting.
outlet, cannot be another Elbow or a Tee fitting.
(optional, defaults to None)
- ``angle (float * u.deg)``: The angle of the fitting, which must be
found in ``AVAILABLE_ANGLES`` (recommended, defaults to 90 °)
- ``id (float * u.inch)``: The inner diameter.
(recommended, defaults to 0.848 * u.inch)
"""
AVAILABLE_ANGLES = [90 * u.deg, 45 * u.deg]
def __init__(self, **kwargs):
self.angle = 90 * u.deg
self.id = 0.848 * u.inch
super().__init__(**kwargs)
self._set_k_minor()
if 'size' in kwargs:
self.id = self._get_id(self.size)
elif 'id' in kwargs:
self.size = self._get_size(self.id)
self._rep_ok()
def _set_k_minor(self):
"""Sets k minor"""
if self.angle == 45 * u.deg:
self.k_minor = hl.EL45_K_MINOR
elif self.angle == 90 * u.deg:
self.k_minor = hl.EL90_K_MINOR
def _get_size(self, id_):
"""Get the size based off the inner diameter.
Args:
- ``id_ (float * u.inch)``: Inner diameter
"""
myindex = (np.abs(AVAILABLE_FITTING_IDS - id_)).argmin()
self.id = AVAILABLE_FITTING_IDS[myindex]
return AVAILABLE_FITTING_SIZES[myindex]
def _get_id(self, size):
"""Get the inner diameter based off the size.
Args:
- ``size (float * u.inch)``: Nominal Size
"""
myindex = (np.abs(AVAILABLE_FITTING_SIZES - size)).argmin()
self.size = AVAILABLE_FITTING_SIZES[myindex]
return AVAILABLE_FITTING_IDS[myindex]
@property
def headloss(self):
"""The headloss"""
return pc.headloss_minor_elbow(self.q, self.id, self.k_minor).to(u.cm)
def format_print(self):
"""The string representation for an Elbow Fitting."""
return 'Elbow: (Size: {}, ID: {}, Angle: {})'.format(
self.size, self.id, self.angle)
def _rep_ok(self):
"""Verify that this representation of a Elbow is valid."""
if self.angle not in self.AVAILABLE_ANGLES:
raise ValueError('angle must be in ', self.AVAILABLE_ANGLES)
if self.next is not None and self.size != self.next.size:
raise ValueError('The next component doesn\'t have the same size.')
|
class Elbow(PipelineComponent):
'''Design class for an Elbow
Instantiate this class to create a readily constructible Elbow fitting and
calculate its hydraulic features.
``Elbow``'s may be instantiated from a nominal size (to fit into an existing
pipeline) or inner diameter (to follow hydraulic constraints), but not both.
Constants:
- ``AVAILABLE_ANGLES (int * u.deg list)``: The possible angles for this
fitting.
Design Inputs:
- ``q (float * u.L/u.s)``: Flow rate (recommended, defaults to 20L/s)
- ``temp (float * u.degC)``: Water temperature
(recommended, defaults to 20°C)
- ``size (float * u.inch)``: The nominal size
(recommended, defaults to 0.5 in.)
- ``fluid_type (str)``: Fluid type. Must be 'water', 'pacl', or 'alum'
(optional, defaults to 'water')
- ``next (PipelineComponent)``: The next pipeline component after the
outlet, cannot be another Elbow or a Tee fitting.
outlet, cannot be another Elbow or a Tee fitting.
outlet, cannot be another Elbow or a Tee fitting.
(optional, defaults to None)
- ``angle (float * u.deg)``: The angle of the fitting, which must be
found in ``AVAILABLE_ANGLES`` (recommended, defaults to 90 °)
- ``id (float * u.inch)``: The inner diameter.
(recommended, defaults to 0.848 * u.inch)
'''
def __init__(self, **kwargs):
pass
def _set_k_minor(self):
'''Sets k minor'''
pass
def _get_size(self, id_):
'''Get the size based off the inner diameter.
Args:
- ``id_ (float * u.inch)``: Inner diameter
'''
pass
def _get_id(self, size):
'''Get the inner diameter based off the size.
Args:
- ``size (float * u.inch)``: Nominal Size
'''
pass
@property
def headloss(self):
'''The headloss'''
pass
def format_print(self):
'''The string representation for an Elbow Fitting.'''
pass
def _rep_ok(self):
'''Verify that this representation of a Elbow is valid.'''
pass
| 9 | 7 | 7 | 1 | 5 | 2 | 2 | 1.06 | 1 | 2 | 0 | 0 | 7 | 4 | 7 | 46 | 93 | 19 | 36 | 16 | 27 | 38 | 32 | 15 | 24 | 3 | 6 | 1 | 13 |
3,255 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/design/lfom.py
|
aguaclara.design.lfom.LFOM
|
class LFOM(Component):
"""Design and AguaClara plant's LFOM.
Design Inputs:
- ``q (float * u.L/u.s)``: Flow rate (recommended, defaults to 20L/s)
- ``temp (float * u.degC)``: Water temperature (recommended, defaults to
20°C)
- ``hl (float * u.cm)``: Head loss (optional, defaults to 20cm)
- ``safety_factor (float)``: Safety factor (optional, defaults to 1.5)
- ``sdr (float)``: Standard dimension ratio (optional, defaults to 26)
- ``drill_bits (float * u.inch array)``: List of drill bits
(optional)
- ``orifice_s (float * u.cm)``: The spacing between orifices (optional,
defaults to 0.5cm)
- ``min_row_n (int)``: Minimum number of rows of orifices (optional,
defaults to 4)
- ``max_row_n (int)``: Maximum number of rows of orifices (optional,
defaults to 10)
"""
def __init__(self, **kwargs):
self.hl = 20.0 * u.cm
self.safety_factor = 1.5
self.sdr = 26.0
self.drill_bits = drills.DRILL_BITS_D_IMPERIAL
self.orifice_s = 0.5 * u.cm
self.min_row_n = 4
self.max_row_n = 10
super().__init__(**kwargs)
def stout_w_per_flow(self, h):
"""The width of a stout weir at a given elevation.
Args:
- ``h (float * u.m)``: Elevation height
"""
w_per_flow = 2 / ((2 * u.gravity * h) ** (1 / 2) *
con.VC_ORIFICE_RATIO * np.pi * self.hl)
return w_per_flow.to_base_units()
@property
def row_n(self):
""" The number of rows."""
N_estimated = (self.hl * np.pi / (2 * self.stout_w_per_flow(self.hl) * \
self.q)).to(u.dimensionless)
row_n = min(self.max_row_n,
max(self.min_row_n, math.trunc(N_estimated.magnitude)))
return row_n
@property
def row_b(self):
"""The distance center to center between each row of orifices."""
return self.hl / self.row_n
@property
def vel_critical(self):
"""The average vertical velocity of the water inside the LFOM pipe
at the bottom of the orfices."""
return (4 / (3 * math.pi) * (2 * u.gravity * self.hl) ** \
(1 / 2)).to(u.m/u.s)
@property
def pipe_a_min(self):
"""The minimum cross-sectional area of the LFOM pipe assuring
a safety factor."""
return (self.safety_factor * self.q / self.vel_critical).to(u.cm**2)
@property
def pipe_nd(self):
"""The nominal diameter of the LFOM pipe"""
ID = pc.diam_circle(self.pipe_a_min)
return pipe.ND_SDR_available(ID, self.sdr)
@property
def top_row_orifice_a(self):
"""The orifice area corresponding to the top row of orifices."""
z = self.hl - 0.5 * self.row_b
return self.stout_w_per_flow(z) * self.q * self.row_b
@property
def orifice_d_max(self):
"""The maximum orifice diameter."""
return pc.diam_circle(self.top_row_orifice_a)
@property
def orifice_d(self):
"""The actual orifice diameter."""
maxdrill = min(self.row_b, self.orifice_d_max)
return ut.floor_nearest(maxdrill, self.drill_bits)
@property
def drill_bit_a(self):
"""The area of the actual drill bit."""
return pc.area_circle(self.orifice_d)
@property
def orifice_n_max_per_row(self):
"""The max number of orifices allowed in each row."""
c = math.pi * pipe.ID_SDR(self.pipe_nd, self.sdr)
b = self.orifice_d + self.orifice_s
return math.floor(c/b)
@property
def q_per_row(self):
"""An array of flow at each row."""
return np.linspace(1 / self.row_n, 1, self.row_n)*self.q
@property
def orifice_h_per_row(self):
"""The height of the center of each row of orifices."""
height_orifices = (np.linspace(0, self.row_n - 1, self.row_n)) * \
self.row_b + 0.5 * self.orifice_d
return height_orifices
def q_submerged(self, row_n, orifice_n_per_row):
"""The flow rate through some number of submerged rows.
Args:
- ``row_n``: Number of submerged rows
"""
flow = 0 * u.L / u.s
for i in range(row_n):
flow = flow + (orifice_n_per_row[i] * (
pc.flow_orifice_vert(self.orifice_d,
self.row_b*(row_n + 1)
- self.orifice_h_per_row[i],
con.VC_ORIFICE_RATIO)))
return flow.to(u.L / u.s)
@property
def orifice_n_per_row(self):
"""The number of orifices at each level."""
h = self.row_b - 0.5*self.orifice_d
flow_per_orifice = pc.flow_orifice_vert(self.orifice_d, h,
con.VC_ORIFICE_RATIO)
n = np.zeros(self.row_n)
for i in range(self.row_n):
flow_needed = self.q_per_row[i] - self.q_submerged(i, n)
n_orifices_real = (flow_needed / \
flow_per_orifice).to(u.dimensionless)
n[i] = min((max(0, round(n_orifices_real))),
self.orifice_n_max_per_row)
return n
@property
def error_per_row(self):
"""The error of the design based off the predicted flow rate and
the actual flow rate."""
q_error = np.zeros(self.row_n)
for i in range(self.row_n):
actual_flow = self.q_submerged(i, self.orifice_n_per_row)
q_error[i] = (((actual_flow - self.q_per_row[i]) / \
self.q_per_row[i]).to(u.dimensionless)).magnitude
return q_error
|
class LFOM(Component):
'''Design and AguaClara plant's LFOM.
Design Inputs:
- ``q (float * u.L/u.s)``: Flow rate (recommended, defaults to 20L/s)
- ``temp (float * u.degC)``: Water temperature (recommended, defaults to
20°C)
- ``hl (float * u.cm)``: Head loss (optional, defaults to 20cm)
- ``safety_factor (float)``: Safety factor (optional, defaults to 1.5)
- ``sdr (float)``: Standard dimension ratio (optional, defaults to 26)
- ``drill_bits (float * u.inch array)``: List of drill bits
(optional)
- ``orifice_s (float * u.cm)``: The spacing between orifices (optional,
defaults to 0.5cm)
- ``min_row_n (int)``: Minimum number of rows of orifices (optional,
defaults to 4)
- ``max_row_n (int)``: Maximum number of rows of orifices (optional,
defaults to 10)
'''
def __init__(self, **kwargs):
pass
def stout_w_per_flow(self, h):
'''The width of a stout weir at a given elevation.
Args:
- ``h (float * u.m)``: Elevation height
'''
pass
@property
def row_n(self):
''' The number of rows.'''
pass
@property
def row_b(self):
'''The distance center to center between each row of orifices.'''
pass
@property
def vel_critical(self):
'''The average vertical velocity of the water inside the LFOM pipe
at the bottom of the orfices.'''
pass
@property
def pipe_a_min(self):
'''The minimum cross-sectional area of the LFOM pipe assuring
a safety factor.'''
pass
@property
def pipe_nd(self):
'''The nominal diameter of the LFOM pipe'''
pass
@property
def top_row_orifice_a(self):
'''The orifice area corresponding to the top row of orifices.'''
pass
@property
def orifice_d_max(self):
'''The maximum orifice diameter.'''
pass
@property
def orifice_d_max(self):
'''The actual orifice diameter.'''
pass
@property
def drill_bit_a(self):
'''The area of the actual drill bit.'''
pass
@property
def orifice_n_max_per_row(self):
'''The max number of orifices allowed in each row.'''
pass
@property
def q_per_row(self):
'''An array of flow at each row.'''
pass
@property
def orifice_h_per_row(self):
'''The height of the center of each row of orifices.'''
pass
def q_submerged(self, row_n, orifice_n_per_row):
'''The flow rate through some number of submerged rows.
Args:
- ``row_n``: Number of submerged rows
'''
pass
@property
def orifice_n_per_row(self):
'''The number of orifices at each level.'''
pass
@property
def error_per_row(self):
'''The error of the design based off the predicted flow rate and
the actual flow rate.'''
pass
| 32 | 17 | 6 | 0 | 5 | 1 | 1 | 0.46 | 1 | 2 | 0 | 0 | 17 | 7 | 17 | 44 | 155 | 21 | 92 | 59 | 60 | 42 | 65 | 45 | 47 | 2 | 5 | 1 | 20 |
3,256 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/design/floc.py
|
aguaclara.design.floc.Flocculator
|
class Flocculator(Component):
"""Design an AguaClara plant's flocculator.
A flocculator's design relies on the entrance tank's design in the same
plant, but assumed/default values may be used to design a flocculator by
itself. To design these components in tandem, use
:class:`aguaclara.design.ent_floc.EntTankFloc`.
Attributes:
- ``BAFFLE_K (float)``: Minor loss coefficient around a baffle edge
- ``CHAN_N_MIN (int)``: Minimum channel number
- ``HS_RATIO_MIN (float)``: Minimum H/S ratio
- ``HS_RATIO_MAX (float)``: Maximum H/S ratio
- ``SDR (float)``: Standard dimension ratio
- ``OBSTACLE_OFFSET (bool)``: Whether the baffle obstacles are offset
from each other
Design Inputs:
- ``q (float * u.L/u.s)``: Flow rate (required)
- ``temp (float * u.degC)``: Water temperature (optional, defaults to
20°C)
- ``ent_l (float * u.m)``: Entrance tank length
(recommmended, defaults to 1.5m)
- ``chan_w_max (float * u.inch)``: Maximum width (optional, defaults to
42")
- ``l_max (float * u.m)``: Maximum length (optional, defaults to 6m)
- ``gt (float)``: Collision potential (optional, defaults to 37000)
- ``hl (float * u.cm)``: Head loss (optional, defaults to 40cm)
- ``end_water_depth (float * u.m)``: Depth at the end
(optional, defaults to 2m)
- ``drain_t (float * u.min)``: Drain time (optional,
defaults to 30 mins)
- ``polycarb_sheet_w (float * u.inch)``: Width of polycarbonate sheets
used to construct baffles (optional, defaults to 42 in)
- ``sed_chan_inlet_w_pre_weir (float * u.inch)``: Width of the inlet
sedimentation channel pre-weir (optional, defaults to 42 in)
- ``dividing_wall_thickness (float * u.cm)``: Thickness of dividing
walls between each flocculator channel (optional, defaults to 15 cm)
- ``chan_n_parity (str)``: Parity of the number of channels. Can be
\'even\', \'odd\', or \'any\' (optional, defaults to \'even\')
"""
BAFFLE_K = 2.5
CHAN_N_MIN = 2
HS_RATIO_MIN = 3.0
HS_RATIO_MAX = 6.0
SDR = 41.0 # This is an expert input in ent, should this be an expert
# input as well? -Oliver L., oal22, 5 Jun 19
OBSTACLE_OFFSET = True
_onshape_url = (
"https://cad.onshape.com/documents/c3a8ce032e33ebe875b9aab4/w/de9ad5474448b34f33fef097/e/08f41d8bdd9a9c90ab396f8a"
)
def __init__(self, **kwargs):
self.ent_l = 1.5 * u.m
self.chan_w_max = 42.0 * u.inch
self.l_max = 6.0 * u.m
self.gt = 37000
self.hl = 40.0 * u.cm
self.end_water_depth = 2.0 * u.m
self.drain_t = 30.0 * u.min
self.spec = 'sdr41'
self.drain_pipe = Pipe()
self.subcomponents = [self.drain_pipe]
self.polycarb_sheet_w = 42.0 * u.inch
self.sed_chan_inlet_w_pre_weir = 42.0 * u.inch
self.dividing_wall_thickness = 15.0 * u.cm
self.chan_n_parity = 'even'
super().__init__(**kwargs)
self._set_drain_pipe()
super().set_subcomponents()
if self.chan_n_parity not in ('even', 'odd', 'any'):
raise AttributeError(
'chan_n_parity must be set to \'even\', \'odd\', or \'any\'.'
)
@property
def vel_grad_avg(self):
"""The average velocity gradient of water."""
vel_grad_avg = ((u.standard_gravity * self.hl) /
(pc.viscosity_kinematic_water(self.temp) * self.gt)).to(u.s ** -1)
return vel_grad_avg
@property
def retention_time(self):
"""The hydraulic retention time neglecting the volume
created by head loss.
"""
retention_time = (self.gt / self.vel_grad_avg).to(u.s)
return retention_time
@property
def vol(self):
"""The target volume (not counting the volume added by head loss)."""
return (self.q * self.retention_time).to(u.m ** 3)
@property
def chan_w_min_hs_ratio(self):
"""The minimum channel width."""
chan_w_min_hs_ratio = (
(self.HS_RATIO_MIN * self.q / self.end_water_depth) *
(
self.BAFFLE_K / (
2 * self.end_water_depth *
pc.viscosity_kinematic_water(self.temp) *
self.vel_grad_avg ** 2
)
) ** (1/3)
).to(u.cm)
return chan_w_min_hs_ratio
@property
def chan_w_min(self):
"""The minimum channel width."""
return ut.min(self.chan_w_min_hs_ratio, self.polycarb_sheet_w).to(u.cm)
@property
def chan_n(self):
"""The minimum number of channels based on the maximum
possible channel width and the maximum length of the channels.
"""
if self.q < 16 * u.L / u.s:
return 1
else:
chan_n = ((
(self.vol /
(self.polycarb_sheet_w * self.end_water_depth)
) + self.ent_l
) / self.chan_l).to_base_units()
if self.chan_n_parity == 'even':
return ut.ceil_step(chan_n, step=2)
elif self.chan_n_parity == 'odd':
return ut.ceil_step(chan_n, step=2) - 1
elif self.chan_n_parity == 'any':
return ut.ceil_step(chan_n, step=1)
@property
def chan_w_min_gt(self):
"""The channel width minimum regarding the collision potential."""
chan_w_min_gt = self.vol / (
self.end_water_depth * (self.chan_n * self.chan_l - self.ent_l)
)
return chan_w_min_gt.to(u.cm)
@property
def chan_w(self):
"""The channel width."""
chan_w = ut.ceil_step(
ut.max(self.chan_w_min_gt, self.chan_w_min),
step=1 * u.cm
)
return chan_w
@property
def l_max_vol(self):
"""The maximum length depeneding on the volume."""
l_max_vol = self.vol / \
(self.CHAN_N_MIN * self.chan_w_min * self.end_water_depth)
return l_max_vol.to(u.m)
@property
def chan_l(self):
"""The channel length."""
chan_l = min(self.l_max, self.l_max_vol)
return chan_l.to_base_units()
@property
def expansion_h_max(self):
""""The maximum distance between expansions for the largest
allowable H/S ratio.
"""
expansion_h_max = (
(
(self.BAFFLE_K /
(
2 * pc.viscosity_kinematic_water(self.temp) *
(self.vel_grad_avg ** 2)
)
) *
(self.q * self.HS_RATIO_MAX / self.chan_w) ** 3
) ** (1/4)
).to(u.m)
return expansion_h_max
@property
def expansion_n(self):
"""The minimum number of expansions per baffle space."""
return np.ceil(self.end_water_depth / self.expansion_h_max)
@property
def expansion_h(self):
"""The height between flow expansions."""
return (self.end_water_depth / self.expansion_n).to(u.cm)
@property
def baffle_s(self):
"""The spacing between baffles."""
baffle_s = (
(self.BAFFLE_K /
(
(2 * self.expansion_h * (self.vel_grad_avg ** 2) *
pc.viscosity_kinematic_water(self.temp))
).to_base_units()
) ** (1/3) *
self.q / self.chan_w
).to(u.cm)
return baffle_s
@property
def obstacle_n(self):
"""The number of obstacles per baffle."""
return self.end_water_depth / self.expansion_h - 1
@property
def contraction_s(self):
"""The space in the baffle by which the flow contracts."""
return self.baffle_s * 0.6
@property
def obstacle_pipe_od(self):
"""The outer diameter of an obstacle pipe. If the available pipe is
greater than 1.5 inches, the obstacle offset will become false."""
pipe_od = pipes.OD_available(self.contraction_s)
if pipe_od > 1.5 * u.inch:
self.OBSTACLE_OFFSET = False
pipe_od = pipes.OD_available(pipe_od / 2)
return pipe_od
def _set_drain_pipe(self):
drain_k_minor = \
hl.PIPE_ENTRANCE_K_MINOR + \
hl.PIPE_ENTRANCE_K_MINOR + \
hl.PIPE_EXIT_K_MINOR
chan_pair_a = 2 * self.chan_l * self.chan_w
drain_id = (
np.sqrt(8 * chan_pair_a / (np.pi * self.drain_t) *
np.sqrt(
self.end_water_depth * drain_k_minor /
(2 * u.standard_gravity)
)
)
).to_base_units()
self.drain_pipe = Pipe(
id=drain_id,
k_minor=drain_k_minor,
spec=self.spec
)
@property
def onshape_url_configured(self):
# Make the configuration string for the flocculator concrete. {{ and }}
# are used so that str.format() doesn't recognize them.
concrete_config = (
'{{"w_channel":"{}", "h_channel":"{}", "l_channel":"{}", "s_baffle"'
':"{}", "n_channel":{}, "t_wall":"{}"}}'.format(
self.chan_w,
self.end_water_depth,
self.chan_l,
self.baffle_s,
self.chan_n,
self.dividing_wall_thickness
)
)
# concrete_config = quote_plus(concrete_config)
encoded_config = '?configuration='
encoded_config += quote_plus('Concrete_config=' + concrete_config + ';')
encoded_config += quote_plus('Channel_L=' + str(self.chan_l) + ';')
configured_url = self._onshape_url + encoded_config
return configured_url
|
class Flocculator(Component):
'''Design an AguaClara plant's flocculator.
A flocculator's design relies on the entrance tank's design in the same
plant, but assumed/default values may be used to design a flocculator by
itself. To design these components in tandem, use
:class:`aguaclara.design.ent_floc.EntTankFloc`.
Attributes:
- ``BAFFLE_K (float)``: Minor loss coefficient around a baffle edge
- ``CHAN_N_MIN (int)``: Minimum channel number
- ``HS_RATIO_MIN (float)``: Minimum H/S ratio
- ``HS_RATIO_MAX (float)``: Maximum H/S ratio
- ``SDR (float)``: Standard dimension ratio
- ``OBSTACLE_OFFSET (bool)``: Whether the baffle obstacles are offset
from each other
Design Inputs:
- ``q (float * u.L/u.s)``: Flow rate (required)
- ``temp (float * u.degC)``: Water temperature (optional, defaults to
20°C)
- ``ent_l (float * u.m)``: Entrance tank length
(recommmended, defaults to 1.5m)
- ``chan_w_max (float * u.inch)``: Maximum width (optional, defaults to
42")
- ``l_max (float * u.m)``: Maximum length (optional, defaults to 6m)
- ``gt (float)``: Collision potential (optional, defaults to 37000)
- ``hl (float * u.cm)``: Head loss (optional, defaults to 40cm)
- ``end_water_depth (float * u.m)``: Depth at the end
(optional, defaults to 2m)
- ``drain_t (float * u.min)``: Drain time (optional,
defaults to 30 mins)
- ``polycarb_sheet_w (float * u.inch)``: Width of polycarbonate sheets
used to construct baffles (optional, defaults to 42 in)
- ``sed_chan_inlet_w_pre_weir (float * u.inch)``: Width of the inlet
sedimentation channel pre-weir (optional, defaults to 42 in)
- ``dividing_wall_thickness (float * u.cm)``: Thickness of dividing
walls between each flocculator channel (optional, defaults to 15 cm)
- ``chan_n_parity (str)``: Parity of the number of channels. Can be
'even', 'odd', or 'any' (optional, defaults to 'even')
'''
def __init__(self, **kwargs):
pass
@property
def vel_grad_avg(self):
'''The average velocity gradient of water.'''
pass
@property
def retention_time(self):
'''The hydraulic retention time neglecting the volume
created by head loss.
'''
pass
@property
def vol(self):
'''The target volume (not counting the volume added by head loss).'''
pass
@property
def chan_w_min_hs_ratio(self):
'''The minimum channel width.'''
pass
@property
def chan_w_min_hs_ratio(self):
'''The minimum channel width.'''
pass
@property
def chan_n(self):
'''The minimum number of channels based on the maximum
possible channel width and the maximum length of the channels.
'''
pass
@property
def chan_w_min_gt(self):
'''The channel width minimum regarding the collision potential.'''
pass
@property
def chan_w_min_hs_ratio(self):
'''The channel width.'''
pass
@property
def l_max_vol(self):
'''The maximum length depeneding on the volume.'''
pass
@property
def chan_l(self):
'''The channel length.'''
pass
@property
def expansion_h_max(self):
'''"The maximum distance between expansions for the largest
allowable H/S ratio.
'''
pass
@property
def expansion_n(self):
'''The minimum number of expansions per baffle space.'''
pass
@property
def expansion_h_max(self):
'''The height between flow expansions.'''
pass
@property
def baffle_s(self):
'''The spacing between baffles.'''
pass
@property
def obstacle_n(self):
'''The number of obstacles per baffle.'''
pass
@property
def contraction_s(self):
'''The space in the baffle by which the flow contracts.'''
pass
@property
def obstacle_pipe_od(self):
'''The outer diameter of an obstacle pipe. If the available pipe is
greater than 1.5 inches, the obstacle offset will become false.'''
pass
def _set_drain_pipe(self):
pass
@property
def onshape_url_configured(self):
pass
| 39 | 18 | 9 | 1 | 8 | 1 | 1 | 0.37 | 1 | 4 | 1 | 0 | 20 | 14 | 20 | 47 | 279 | 34 | 180 | 77 | 141 | 66 | 93 | 59 | 72 | 5 | 5 | 2 | 26 |
3,257 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/design/filter.py
|
aguaclara.design.filter.Filter
|
class Filter(Component):
sand_layer_thick = 20 *u.cm
n_backwash_manifold_diameter = 4 * u.inch
max_filtration_head_loss = 30 * u.cm
@property
def n_tanks():
tank = math.ceil(self.q/40)
return (tank.magnitude)*2
@property
def flow_rate_per_tank():
n_tanks = n_tanks()
return flow_rate/n_tanks
|
class Filter(Component):
@property
def n_tanks():
pass
@property
def flow_rate_per_tank():
pass
| 5 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 29 | 15 | 3 | 12 | 10 | 7 | 0 | 10 | 8 | 7 | 1 | 5 | 0 | 2 |
3,258 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/design/ent_floc.py
|
aguaclara.design.ent_floc.EntTankFloc
|
class EntTankFloc(Component):
"""Design an AguaClara plant's entrance tank/flocculator assembly.
The designs of the LFOM, entrance tank, and flocculator in an AguaClara
water treatment plant are interdependent. Use this class instead of the
classes of the individual components to design all three at once.
Design Inputs:
- ``q (float * u.L / u.s)``: Flow rate (recommended,
defaults to 20L/s)
- ``temp (float * u.degC)``: Water temperature (recommended,
defaults to 20°C)
- ``ent (EntranceTank)``: Entrance Tank
(optional, see :class:`aguaclara.design.ent.EntranceTank`
for defaults)
- ``floc (Flocculator)``: Flocculator
(optional, see :class:`aguaclara.design.floc.Flocculator` for
defaults)
- ``lfom (LFOM)``: Linear Flow Orifice Meter
(optional, see :class:`aguaclara.design.lfom.LFOM` for defaults)
"""
def __init__(self, **kwargs):
self.ent = EntranceTank()
self.floc = Flocculator()
self.lfom = LFOM()
self.subcomponents = [self.ent, self.floc, self.lfom]
super().__init__(**kwargs)
super().set_subcomponents()
self._design_ent_floc(self.floc.ent_l)
def _design_ent_floc(self, ent_l):
"""Design the entrance tank and flocculator in tandem.
Each subcomponent is redesigned until the expected length of the
entrance tank (used to design the flocculator) is close enough to the
actual length of the entrance tank (which should accomodate the
flocculator's channel width).
Args:
- ``ent_l (float * u.m)``: The initial guess for the entrance tank's
length, used to design the first iteration of the flocculator.
"""
# Design the flocculator using a guess of the entrance tank's length.
self.floc.ent_l = ent_l
# Design the entrance tank using the flocculator's channel width.
self.ent.floc_chan_w = self.floc.chan_w
# Recalculate if the actual length of the entrance tank is not close
# enough.
if np.abs(self.ent.l.to(u.m) - ent_l) / self.ent.l > 0.01:
self._design_ent_floc(self.ent.l)
|
class EntTankFloc(Component):
'''Design an AguaClara plant's entrance tank/flocculator assembly.
The designs of the LFOM, entrance tank, and flocculator in an AguaClara
water treatment plant are interdependent. Use this class instead of the
classes of the individual components to design all three at once.
Design Inputs:
- ``q (float * u.L / u.s)``: Flow rate (recommended,
defaults to 20L/s)
- ``temp (float * u.degC)``: Water temperature (recommended,
defaults to 20°C)
- ``ent (EntranceTank)``: Entrance Tank
(optional, see :class:`aguaclara.design.ent.EntranceTank`
for defaults)
- ``floc (Flocculator)``: Flocculator
(optional, see :class:`aguaclara.design.floc.Flocculator` for
defaults)
- ``lfom (LFOM)``: Linear Flow Orifice Meter
(optional, see :class:`aguaclara.design.lfom.LFOM` for defaults)
'''
def __init__(self, **kwargs):
pass
def _design_ent_floc(self, ent_l):
'''Design the entrance tank and flocculator in tandem.
Each subcomponent is redesigned until the expected length of the
entrance tank (used to design the flocculator) is close enough to the
actual length of the entrance tank (which should accomodate the
flocculator's channel width).
Args:
- ``ent_l (float * u.m)``: The initial guess for the entrance tank's
length, used to design the first iteration of the flocculator.
'''
pass
| 3 | 2 | 16 | 3 | 7 | 7 | 2 | 2.21 | 1 | 4 | 3 | 0 | 2 | 4 | 2 | 29 | 54 | 9 | 14 | 7 | 11 | 31 | 14 | 7 | 11 | 2 | 5 | 1 | 3 |
3,259 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/design/ent.py
|
aguaclara.design.ent.EntranceTank
|
class EntranceTank(Component):
"""Design an AguaClara plant's entrance tank.
An entrance tank's design relies on the LFOM's and flocculator's design in
the same plant, but assumed/default values may be used to design an
entrance tank by itself. To design these components in tandem, use
:class:`aguaclara.design.ent_floc.EntTankFloc`.
Design Inputs:
- ``q (float * u.L / u.s)``: Flow rate (recommended, defaults to 20L/s)
- ``temp (float * u.degC)``: Water temperature (recommended, defaults to
20°C)
- ``lfom_nd (float * u.inch)``: The LFOM's nominal diameter (recommended,
defaults to 2")
- ``floc_chan_w (float * u.inch)``: The flocculator's channel width
(recommended, defaults to 42")
- ``floc_chan_depth (float * u.m)``: The flocculator's channel depth
(recommended, defaults to 2m)
- ``plate_s (float * u.cm)``: The spacing between plates in a plate
settler (optional, defaults to 2.5cm)
- ``plate_thickness (float * u.deg)``: The thickness of a plate in a
plate settler (optional, defaults to 2mm)
- ``plate_angle (float * u.deg)``: The angle of the plate settler
(optional, defaults to 60 degrees)
- ``plate_capture_vel (float * u.mm / u.s)``: The capture velocity of the
plate settler (optional, defaults to 8m/s)
- ``fab_s(float * u.cm)``: The space needed for a person to remove
the drain pipe (optional, defaults to 5cm)
- ``sdr (float)``: Standard demension ratio (optional,
defaults to 41)
"""
def __init__(self, **kwargs):
self.lfom_nd = 2.0 * u.inch # May be innacurate, check with Monroe -Oliver L., oal22, 4 Jun '19
self.floc_chan_w = 42.0 * u.inch
self.floc_end_depth = 2.0 * u.m
self.plate_s = 2.5 * u.cm
self.plate_thickness = 2.0 * u.mm
self.plate_angle = 50.0 * u.deg
self.plate_capture_vel = 8.0 * u.mm / u.s
self.fab_s = 5.0 * u.cm
self.spec = 'sdr41'
self.drain_pipe = Pipe()
self.subcomponents = [self.drain_pipe]
super().__init__(**kwargs)
self._set_drain_pipe()
super().set_subcomponents()
def _set_drain_pipe(self):
"""The inner diameter of the entrance tank drain pipe."""
drain_pipe_k_minor = \
hl.PIPE_ENTRANCE_K_MINOR + hl.PIPE_EXIT_K_MINOR + hl.EL90_K_MINOR
nu = pc.viscosity_kinematic_water(self.temp)
drain_id = pc.diam_pipe(self.q,
self.floc_end_depth,
self.floc_end_depth,
nu,
mat.PVC_PIPE_ROUGH,
drain_pipe_k_minor)
self.drain_pipe = Pipe(
id = drain_id,
k_minor = drain_pipe_k_minor,
spec = self.spec
)
@property
def plate_n(self):
"""The number of plates in the plate settlers."""
num_plates_as_float = \
np.sqrt(
(self.q / (
(self.plate_s + self.plate_thickness) * self.floc_chan_w *
self.plate_capture_vel *
np.sin(self.plate_angle.to(u.rad)).item()
)).to(u.dimensionless)
)
num_plates_as_int = np.ceil(num_plates_as_float)
return num_plates_as_int # This calculates to be too low. -Oliver
@property
def plate_l(self):
"""The length of the plates in the plate settlers."""
plate_l = (
self.q / (
self.plate_n * self.floc_chan_w * self.plate_capture_vel *
np.cos(self.plate_angle.to(u.rad))
)
) - (self.plate_s * np.tan(self.plate_angle.to(u.rad)))
plate_l_rounded = ut.ceil_step(plate_l.to(u.cm), 1.0 * u.cm)
return plate_l_rounded
@property
def l(self):
"""The length of the entrance tank."""
plate_array_thickness = \
(self.plate_thickness * self.plate_n) + \
(self.plate_s * (self.plate_n - 1))
l = self.drain_pipe.od + (self.fab_s * 2) + \
(
plate_array_thickness * np.cos(((90 * u.deg) -
self.plate_angle).to(u.rad))
) + \
(self.plate_l * np.cos(self.plate_angle.to(u.rad))) + \
(self.lfom_nd * 2)
return l
|
class EntranceTank(Component):
'''Design an AguaClara plant's entrance tank.
An entrance tank's design relies on the LFOM's and flocculator's design in
the same plant, but assumed/default values may be used to design an
entrance tank by itself. To design these components in tandem, use
:class:`aguaclara.design.ent_floc.EntTankFloc`.
Design Inputs:
- ``q (float * u.L / u.s)``: Flow rate (recommended, defaults to 20L/s)
- ``temp (float * u.degC)``: Water temperature (recommended, defaults to
20°C)
- ``lfom_nd (float * u.inch)``: The LFOM's nominal diameter (recommended,
defaults to 2")
- ``floc_chan_w (float * u.inch)``: The flocculator's channel width
(recommended, defaults to 42")
- ``floc_chan_depth (float * u.m)``: The flocculator's channel depth
(recommended, defaults to 2m)
- ``plate_s (float * u.cm)``: The spacing between plates in a plate
settler (optional, defaults to 2.5cm)
- ``plate_thickness (float * u.deg)``: The thickness of a plate in a
plate settler (optional, defaults to 2mm)
- ``plate_angle (float * u.deg)``: The angle of the plate settler
(optional, defaults to 60 degrees)
- ``plate_capture_vel (float * u.mm / u.s)``: The capture velocity of the
plate settler (optional, defaults to 8m/s)
- ``fab_s(float * u.cm)``: The space needed for a person to remove
the drain pipe (optional, defaults to 5cm)
- ``sdr (float)``: Standard demension ratio (optional,
defaults to 41)
'''
def __init__(self, **kwargs):
pass
def _set_drain_pipe(self):
'''The inner diameter of the entrance tank drain pipe.'''
pass
@property
def plate_n(self):
'''The number of plates in the plate settlers.'''
pass
@property
def plate_l(self):
'''The length of the plates in the plate settlers.'''
pass
@property
def l(self):
'''The length of the entrance tank.'''
pass
| 9 | 5 | 14 | 1 | 12 | 1 | 1 | 0.52 | 1 | 2 | 1 | 0 | 5 | 11 | 5 | 32 | 109 | 11 | 66 | 29 | 57 | 34 | 33 | 26 | 27 | 1 | 5 | 0 | 5 |
3,260 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/design/cdc.py
|
aguaclara.design.cdc.CDC
|
class CDC(Component):
"""Design an AguaClara plant's chemical dose controller.
Design Inputs:
- ``q (float * u.L / u.s)``: Flow rate (required)
"""
def __init__(self, **kwargs):
self.hl = 20 * u.cm
self.coag_type='pacl'
if self.coag_type.lower() not in ['pacl', 'alum']:
raise ValueError('coag_type must be either PACl or Alum.')
self.coag_dose_conc_max=100 * u.mg / u.L
self.coag_stock_conc=150 * u.g / u.L
self.coag_stock_conc_est=150 * u.g / u.L # Deprecated since January 2021
self.coag_stock_min_est_time=1 * u.day
self.chem_tank_vol_supplier=[208.198, 450, 600, 750, 1100, 2500] * u.L
self.chem_tank_dimensions_supplier=[
[0.571, 0.851],
[0.85, 0.99],
[0.96, 1.10],
[1.10, 1.02],
[1.10, 1.39],
[1.55, 1.65]
] * u.m
self.train_n=1
self.coag_sack_mass = 25 * u.kg
self.coag_tube_id = 0.125 * u.inch
self.error_ratio=0.1
self.tube_k = 2
super().__init__(**kwargs)
def alum_nu(self, coag_conc):
"""
Return the dynamic viscosity of water at a given temperature.
If given units, the function will automatically convert to Kelvin.
If not given units, the function will assume Kelvin.
This function assumes that the temperature dependence can be explained
based on the effect on water and that there is no confounding effect from
the coagulant.
"""
alum_nu = \
(1 + (4.255 * 10 ** -6) * (coag_conc/(u.kg/u.m**3)).to(u.dimensionless) ** 2.289) * \
pc.viscosity_kinematic_water(self.temp)
return alum_nu
def _alum_nu(self, coag_conc):
"""
.. deprecated::
`_alum_nu` is deprecated; use `alum_nu` instead.
"""
# Deprecated since January 2021
warnings.warn('_alum_nu is deprecated; use alum_nu instead.',
UserWarning)
return self.alum_nu(coag_conc)
def pacl_nu(self, coag_conc):
"""Return the dynamic viscosity of water at a given temperature.
If given units, the function will automatically convert to Kelvin.
If not given units, the function will assume Kelvin.
This function assumes that the temperature dependence can be explained
based on the effect on water and that there is no confounding effect
from the coagulant.
"""
pacl_nu = \
(1 + (2.383 * 10 ** -5) * (coag_conc/(u.kg/u.m**3)).to(u.dimensionless) ** 1.893) * \
pc.viscosity_kinematic_water(self.temp)
return pacl_nu
def _pacl_nu(self, coag_conc):
"""
.. deprecated::
`_pacl_nu` is deprecated; use `pacl_nu` instead.
"""
# Deprecated since January 2021
warnings.warn('_pacl_nu is deprecated; use pacl_nu instead.',
UserWarning)
return self.pacl_nu(coag_conc)
def _coag_nu(self, coag_conc, coag_type):
"""
.. deprecated::
`_coag_nu` is deprecated; use `coag_nu` instead.
"""
# Deprecated since January 2021
warnings.warn('_coag_nu is deprecated; use coag_nu instead.',
UserWarning)
return self.coag_nu(coag_conc, coag_type)
def coag_nu(self, coag_conc, coag_type):
"""Return the dynamic viscosity of water at a given temperature.
If given units, the function will automatically convert to Kelvin.
If not given units, the function will assume Kelvin.
"""
if coag_type.lower() == 'alum':
coag_nu = self.alum_nu(coag_conc)
elif coag_type.lower() == 'pacl':
coag_nu = self.pacl_nu(coag_conc)
return coag_nu
@property
def coag_q_max_est(self):
"""The estimated maximum permissible flow rate of the coagulant stock,
based on a whole number of sacks of coagulant used.
.. deprecated::
`coag_q_max_est` is deprecated; use `coag_q_max` instead, which is
based on the exact user-defined coagulant stock concentration,
`coag_stock_conc`.
"""
# Deprecated since January 2021
warnings.warn('coag_q_max_est is deprecated; use coag_q_max instead,\
which is based on the exact user-defined coagulant stock \
concentration, coag_stock_conc.', UserWarning)
coag_q_max_est = self.q * self.coag_dose_conc_max / \
self.coag_stock_conc_est
return coag_q_max_est
@property
def coag_q_max(self):
"""The maximum permissible flow rate of the coagulant stock."""
coag_q_max = self.q * self.coag_dose_conc_max / self.coag_stock_conc
return coag_q_max.to(u.L / u.s)
@property
def coag_stock_vol(self):
"""The volume of the coagulant stock tank, based on available sizes
from the supplier.
"""
coag_stock_vol = ut.ceil_nearest(
self.coag_stock_min_est_time * self.train_n *
self.coag_q_max,
self.chem_tank_vol_supplier
)
return coag_stock_vol
@property
def coag_sack_n(self):
"""The number of sacks of coagulant needed to make the coagulant stock,
rounded to the nearest whole number.
"""
coag_sack_n = round(
(self.coag_stock_vol * self.coag_stock_conc /
self.coag_sack_mass).to_base_units()
)
return coag_sack_n
# Commented out January 2021
# @property
# def coag_stock_conc(self):
# """The concentration of the coagulant stock."""
# coag_stock_conc = self.coag_sack_n * self.coag_sack_mass / \
# self.coag_stock_vol
# return coag_stock_conc
@property
def coag_stock_time_min(self):
"""The minimum amount of time that the coagulant stock will last."""
return self.coag_stock_vol / (self.train_n * self.coag_q_max)
@property
def coag_stock_nu(self):
"""The kinematic viscosity of the coagulant stock."""
return self.coag_nu(self.coag_stock_conc, self.coag_type)
#==============================================================================
# Small-diameter Tube Design
#==============================================================================
@property
def _coag_tube_q_max(self):
"""The maximum permissible flow through a coagulant tube."""
coag_tube_q_max = ((np.pi * self.coag_tube_id ** 2)/4) * \
np.sqrt((2 * self.error_ratio * self.hl * u.gravity)/self.tube_k)
return coag_tube_q_max.to(u.L / u.s)
@property
def coag_tubes_active_n(self):
"""The number of coagulant tubes in use."""
coag_tubes_active_n = \
np.ceil((self.coag_q_max / self._coag_tube_q_max).to_base_units())
return coag_tubes_active_n
@property
def coag_tubes_n(self):
"""The number of coagulant tubes in use, plus a spare tube for
maintenance.
"""
coag_tubes_n = self.coag_tubes_active_n + 1
return coag_tubes_n
@property
def coag_tube_operating_q_max(self):
"""The maximum flow through a coagulant tube during actual operation."""
coag_tube_operating_q_max = self.coag_q_max / self.coag_tubes_active_n
return coag_tube_operating_q_max
@property
def coag_tube_l(self):
"""The length of a coagulant tube."""
coag_tube_l = (
self.hl * u.gravity * np.pi * self.coag_tube_id ** 4 /
(128 * self.coag_stock_nu * self.coag_tube_operating_q_max)
) - (
8 * self.coag_tube_operating_q_max * self.tube_k /
(128 * np.pi * self.coag_stock_nu)
)
return coag_tube_l.to_base_units()
@property
def coag_tank_r(self):
"""The radius of the coagulant stock tank, based on available sizes
from the supplier."""
index = np.argmax(self.chem_tank_vol_supplier == self.coag_stock_vol)
coag_tank_r = self.chem_tank_dimensions_supplier[index][0] / 2
return coag_tank_r
@property
def coag_tank_h(self):
"""The height of the coagulant stock tank, based on available sizes
from the supplier."""
index = np.argmax(self.chem_tank_vol_supplier == self.coag_stock_vol)
coag_tank_h = self.chem_tank_dimensions_supplier[index][1]
return coag_tank_h
def _DiamTubeAvail(self, en_tube_series = True):
if en_tube_series:
return 1*u.mm
else:
return (1/16)*u.inch
|
class CDC(Component):
'''Design an AguaClara plant's chemical dose controller.
Design Inputs:
- ``q (float * u.L / u.s)``: Flow rate (required)
'''
def __init__(self, **kwargs):
pass
def alum_nu(self, coag_conc):
'''
Return the dynamic viscosity of water at a given temperature.
If given units, the function will automatically convert to Kelvin.
If not given units, the function will assume Kelvin.
This function assumes that the temperature dependence can be explained
based on the effect on water and that there is no confounding effect from
the coagulant.
'''
pass
def _alum_nu(self, coag_conc):
'''
.. deprecated::
`_alum_nu` is deprecated; use `alum_nu` instead.
'''
pass
def pacl_nu(self, coag_conc):
'''Return the dynamic viscosity of water at a given temperature.
If given units, the function will automatically convert to Kelvin.
If not given units, the function will assume Kelvin.
This function assumes that the temperature dependence can be explained
based on the effect on water and that there is no confounding effect
from the coagulant.
'''
pass
def _pacl_nu(self, coag_conc):
'''
.. deprecated::
`_pacl_nu` is deprecated; use `pacl_nu` instead.
'''
pass
def _coag_nu(self, coag_conc, coag_type):
'''
.. deprecated::
`_coag_nu` is deprecated; use `coag_nu` instead.
'''
pass
def coag_nu(self, coag_conc, coag_type):
'''Return the dynamic viscosity of water at a given temperature.
If given units, the function will automatically convert to Kelvin.
If not given units, the function will assume Kelvin.
'''
pass
@property
def coag_q_max_est(self):
'''The estimated maximum permissible flow rate of the coagulant stock,
based on a whole number of sacks of coagulant used.
.. deprecated::
`coag_q_max_est` is deprecated; use `coag_q_max` instead, which is
based on the exact user-defined coagulant stock concentration,
`coag_stock_conc`.
'''
pass
@property
def coag_q_max_est(self):
'''The maximum permissible flow rate of the coagulant stock.'''
pass
@property
def coag_stock_vol(self):
'''The volume of the coagulant stock tank, based on available sizes
from the supplier.
'''
pass
@property
def coag_sack_n(self):
'''The number of sacks of coagulant needed to make the coagulant stock,
rounded to the nearest whole number.
'''
pass
@property
def coag_stock_time_min(self):
'''The minimum amount of time that the coagulant stock will last.'''
pass
@property
def coag_stock_nu(self):
'''The kinematic viscosity of the coagulant stock.'''
pass
@property
def _coag_tube_q_max(self):
'''The maximum permissible flow through a coagulant tube.'''
pass
@property
def coag_tubes_active_n(self):
'''The number of coagulant tubes in use.'''
pass
@property
def coag_tubes_n(self):
'''The number of coagulant tubes in use, plus a spare tube for
maintenance.
'''
pass
@property
def coag_tube_operating_q_max(self):
'''The maximum flow through a coagulant tube during actual operation.'''
pass
@property
def coag_tube_l(self):
'''The length of a coagulant tube.'''
pass
@property
def coag_tank_r(self):
'''The radius of the coagulant stock tank, based on available sizes
from the supplier.'''
pass
@property
def coag_tank_h(self):
'''The height of the coagulant stock tank, based on available sizes
from the supplier.'''
pass
def _DiamTubeAvail(self, en_tube_series = True):
pass
| 35 | 20 | 9 | 0 | 5 | 3 | 1 | 0.6 | 1 | 3 | 0 | 0 | 21 | 13 | 21 | 48 | 236 | 31 | 129 | 64 | 94 | 77 | 82 | 51 | 60 | 3 | 5 | 1 | 25 |
3,261 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/core/pipes.py
|
aguaclara.core.pipes.SCH
|
class SCH(Enum):
# value is the column name for a schedule's wall thickness
SCH40 = 'SCH40Wall'
SCH80 = 'SCH80Wall'
SCH120 = 'SCH120Wall'
SCH160 = 'SCH160Wall'
|
class SCH(Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 6 | 0 | 5 | 5 | 4 | 1 | 5 | 5 | 4 | 0 | 4 | 0 | 0 |
3,262 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/core/pipes.py
|
aguaclara.core.pipes.Pipe
|
class Pipe:
"""A pipe using the SDR system, represented by its nominal diameter (ND) and standard dimension ratio (SDR)"""
def __init__(self, nd,sdr):
self.nd= nd
self.sdr = sdr
@property
def od(self):
"""The outer diameter of the pipe."""
index = (np.abs(np.array(pipedb['NDinch']) - self.nd.magnitude)).argmin()
return pipedb.iloc[index, 1] * u.inch
@property
def id_sdr(self):
"""The inner diameter of the pipe, calculated using the pipe's OD and SDR."""
return (self.od.magnitude * (self.sdr - 2) / self.sdr) * u.inch
@property
def id_sch40(self):
"""
.. deprecated::
`id_sch40` is deprecated; use `id_sch` instead.
"""
warnings.warn('id_sch40 is deprecated; use id_sch instead.', UserWarning)
myindex = (np.abs(np.array(pipedb['NDinch']) - self.nd.magnitude)).argmin()
return (pipedb.iloc[myindex, 1] - 2 * (pipedb.iloc[myindex, 5])) * u.inch
def id_sch(self, schedule):
"""
The inner diameter of this pipe, based on schedule and nominal diameter
:param schedule: the schedule of the pipe (Ex: pipes.SCH.SCH40)
:type schedule: pipes.SCH
:return: The inner diameter of the pipe
:rtype: u.inch
"""
myindex = (np.abs(np.array(pipedb['NDinch']) - self.nd.magnitude)).argmin()
thickness = pipedb.iloc[myindex][schedule.value]
if (thickness == 0):
return schedule ^ " does not exist for this ND"
return (pipedb.iloc[myindex, 1] - 2 * (thickness)) * u.inch
def sch(self, NDarr=None, SCHarr=None):
"""
The nominal diameter and schedule that best fits this pipe's criteria and NDarr and SCHarr
:param NDarr: an array of preferred nominal diameters (Ex: [10]*u.inch). Default: None
:type NDarr: numpy.array * u.inch
:param SCHarr: an array of preferred schedules (Ex: [pipes.SCH.SCH160, pipes.SCH.SCH40]). Default: None
:type SCHarr: pipes.SCH list
:return: (nominal diameter, schedule) tuple or None
:rtype: (u.inch, SCH) or None
"""
# get list of all (ND, SCH) available and return the (ND, SCH) resulting in the least ID
available = SCH_all_available(self.id_sdr, self.sdr, NDarr, SCHarr)
if available==[]:
return None
def sch_based_on_name(n):
if n == SCH.SCH40.name:
return SCH.SCH40
elif n == SCH.SCH80.name:
return SCH.SCH80
elif n == SCH.SCH120.name:
return SCH.SCH120
elif n == SCH.SCH160.name:
return SCH.SCH160
def addID (p):
# find id that goes with nd sch and add it to the tuple
# p is of the structure (ND, schedule name)
# outputs (id, nd, sch) tuple
nd = p[0]
sch = p[1]
row = pipedb.loc[pipedb['NDinch'] == nd.magnitude] # 1 row df
t = row[sch_based_on_name(sch).value].iloc[0]
od = row['ODinch'].iloc[0]
return (od-2*t, nd, sch)
available = list(map(addID, available))
m = min(available)[0]
return list(filter(lambda x: m == x[0], available))[0][1:]
|
class Pipe:
'''A pipe using the SDR system, represented by its nominal diameter (ND) and standard dimension ratio (SDR)'''
def __init__(self, nd,sdr):
pass
@property
def od(self):
'''The outer diameter of the pipe.'''
pass
@property
def id_sdr(self):
'''The inner diameter of the pipe, calculated using the pipe's OD and SDR.'''
pass
@property
def id_sch40(self):
'''
.. deprecated::
`id_sch40` is deprecated; use `id_sch` instead.
'''
pass
def id_sch40(self):
'''
The inner diameter of this pipe, based on schedule and nominal diameter
:param schedule: the schedule of the pipe (Ex: pipes.SCH.SCH40)
:type schedule: pipes.SCH
:return: The inner diameter of the pipe
:rtype: u.inch
'''
pass
def sch(self, NDarr=None, SCHarr=None):
'''
The nominal diameter and schedule that best fits this pipe's criteria and NDarr and SCHarr
:param NDarr: an array of preferred nominal diameters (Ex: [10]*u.inch). Default: None
:type NDarr: numpy.array * u.inch
:param SCHarr: an array of preferred schedules (Ex: [pipes.SCH.SCH160, pipes.SCH.SCH40]). Default: None
:type SCHarr: pipes.SCH list
:return: (nominal diameter, schedule) tuple or None
:rtype: (u.inch, SCH) or None
'''
pass
def sch_based_on_name(n):
pass
def addID (p):
pass
| 12 | 6 | 12 | 1 | 7 | 4 | 2 | 0.62 | 0 | 5 | 1 | 0 | 6 | 2 | 6 | 6 | 84 | 12 | 45 | 25 | 33 | 28 | 39 | 22 | 30 | 5 | 0 | 1 | 14 |
3,263 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/core/physchem.py
|
aguaclara.core.physchem.DeprecatedFunctionError
|
class DeprecatedFunctionError(Exception):
def __init__(self, message):
self.message = message
|
class DeprecatedFunctionError(Exception):
def __init__(self, message):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 11 | 3 | 0 | 3 | 3 | 1 | 0 | 3 | 3 | 1 | 1 | 3 | 0 | 1 |
3,264 |
AguaClara/aguaclara
|
AguaClara_aguaclara/aguaclara/core/cache.py
|
aguaclara.core.cache.HashableObject
|
class HashableObject:
def ac_hash(self):
return tuple(sorted(self.__dict__.items()))
|
class HashableObject:
def ac_hash(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | 1 | 1 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 0 | 0 | 1 |
3,265 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_physchem.py
|
test_physchem.HeadlossFuncsTest
|
class HeadlossFuncsTest(QuantityTest):
"""Test the headloss functions."""
def test_headloss_fric(self):
self.assertWarns(UserWarning, pc.headloss_fric, *(100 * u.m**3/u.s, 2 * u.m, 4 * u.m, 0.001 * u.m**2/u.s, 1 * u.m))
def test_headloss_major_pipe(self):
"""headloss_major_pipe should return known results with known inputs."""
checks = (([100 * u.m**3/u.s, 2 * u.m, 4 * u.m, 0.001 * u.m**2/u.s, 1 * u.m], 34.2549414191127 * u.m),
([100 * u.m**3/u.s, 2 * u.m, 4 * u.m, 0.1 * u.m**2/u.s, 1 * u.m], 10.386744054168654 * u.m),
([100 * u.m**3/u.s, 2 * u.m, 4 * u.m, 0.001 * u.m**2/u.s, 0 * u.m], 2.032838149828097 * u.m),
([46 * u.m**3/u.s, 9 * u.m, 12 * u.m, 0.001 * u.m**2/u.s, 0.03 * u.m], 0.001399778168304583 * u.m),
([55 * u.m**3/u.s, 0.4 * u.m, 2 * u.m, 0.5 * u.m**2/u.s, 0.0001 * u.m], 8926.108171551185 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.headloss_major_pipe(*i[0]), i[1])
def test_headloss_major_pipe_range(self):
"""headloss_major_pipe should raise an error if Length <= 0."""
checks = ([1 * u.m**3/u.s, 1 * u.m, 0 * u.m, 1 * u.m**2/u.s, 1 * u.m],
[1 * u.m**3/u.s, 1 * u.m, -1 * u.m, 1 * u.m**2/u.s, 1 * u.m])
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.headloss_major_pipe, *i)
def test_headloss_exp(self):
self.assertWarns(UserWarning, pc.headloss_exp, *(60 * u.m**3/u.s, 0.9 * u.m, 0.067))
def test_headloss_minor_pipe(self):
"""headloss_minor_pipe should return known results with known input."""
checks = (([60 * u.m**3/u.s, 0.9 * u.m, 0.067], 30.386230766265214 * u.m),
([60 * u.m**3/u.s, 0.9 * u.m, 0.067 * u.dimensionless], 30.386230766265214 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.headloss_minor_pipe(*i[0]), i[1])
def test_headloss_minor_pipe_range(self):
"""headloss_minor_pipe should raise errors when inputs are out of bounds."""
checks = ([0 * u.m**3/u.s, 1 * u.m, 1], [1 * u.m**3/u.s, 0 * u.m, 1],
[1 * u.m**3/u.s, 1 * u.m, -1])
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.headloss_minor_pipe, *i)
def test_headloss(self):
self.assertWarns(UserWarning, pc.headloss, *(100 * u.m**3/u.s, 2 * u.m, 4 * u.m, 0.001 * u.m**2/u.s, 1 * u.m, 2))
def test_headloss_pipe(self):
"""headloss_pipe should return known results with known inputs."""
checks = (([100 * u.m**3/u.s, 2 * u.m, 4 * u.m, 0.001 * u.m**2/u.s, 1 * u.m, 2], 137.57379509731857 * u.m),
([100 * u.m**3/u.s, 2 * u.m, 4 * u.m, 0.1 * u.m**2/u.s, 1 * u.m, 0.4], 31.05051478980984 * u.m),
([100 * u.m**3/u.s, 2 * u.m, 4 * u.m, 0.001 * u.m**2/u.s, 0 * u.m, 1.2], 64.024150356751633 * u.m),
([46 * u.m**3/u.s, 9 * u.m, 12 * u.m, 0.001 * u.m**2/u.s, 0.03 * u.m, 4], 0.10802874052554703 * u.m),
([55 * u.m**3/u.s, 0.4 * u.m, 2 * u.m, 0.5 * u.m**2/u.s, 0.0001 * u.m, 0.12], 10098.131417963332 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.headloss_pipe(*i[0]), i[1])
def test_headloss_fric_rect(self):
self.assertWarns(UserWarning, pc.headloss_fric_rect, *(0.06 * u.m**3/u.s, 3 * u.m, 0.2 * u.m, 4 * u.m, 0.5 * u.m**2/u.s, 0.006 * u.m, True))
def test_headloss_major_rect(self):
"""headloss_major_rect should return known result with known inputs."""
checks = (([0.06 * u.m**3/u.s, 3 * u.m, 0.2 * u.m, 4 * u.m, 0.5 * u.m**2/u.s, 0.006 * u.m, True], 1.3097688246694272 * u.m),
([0.06 * u.m**3/u.s, 3 * u.m, 0.2 * u.m, 4 * u.m, 0.5 * u.m**2/u.s, 0.006 * u.m, False], 4.640841787063992 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.headloss_major_rect(*i[0]), i[1])
def test_headloss_major_rect_range(self):
"""headloss_major_rect should raise an error when Length <=0."""
checks = ((1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 0 * u.m, 1 * u.m**2/u.s, 1 * u.m, 1),
(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, -1 * u.m, 1 * u.m**2/u.s, 1 * u.m, 1))
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.headloss_major_rect, *i)
def test_headloss_exp_rect(self):
self.assertWarns(UserWarning, pc.headloss_exp_rect, *(0.06 * u.m**3/u.s, 2 * u.m, 0.004 * u.m, 1))
def test_headloss_minor_rect(self):
"""headloss_minor_rect should return known result for known input."""
checks = ([0.06 * u.m**3/u.s, 2 * u.m, 0.004 * u.m, 1], 2.8679518490004234 * u.m)
self.assertAlmostEqualQuantity(pc.headloss_minor_rect(*checks[0]), checks[1])
def test_headloss_minor_rect_range(self):
"""headloss_minor_rect should raise errors when inputs are out of bounds."""
checks = ((0 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1), (1 * u.m**3/u.s, 0 * u.m, 1 * u.m, 1),
(1 * u.m**3/u.s, 1 * u.m, 0 * u.m, 1), (1 * u.m**3/u.s, 1 * u.m, 1 * u.m, -1))
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.headloss_minor_rect, *i)
def test_headloss_rect(self):
"""headloss_rect should return known result for known inputs."""
checks = (([0.06 * u.m**3/u.s, 3 * u.m, 0.2 * u.m, 4 * u.m, 1 * u.dimensionless, 0.5 * u.m**2/u.s, 0.006 * u.m, True], 1.3102786827759163 * u.m),
([0.06 * u.m**3/u.s, 3 * u.m, 0.2 * u.m, 4 * u.m, 1, 0.5 * u.m**2/u.s, 0.006 * u.m, False], 4.641351645170481 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.headloss_rect(*i[0]), i[1])
def test_headloss_rect_warning(self):
"""headloss_rect should raise warnings when passed deprecated parameters"""
error_checks = (lambda: pc.headloss_rect(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 4 * u.m, 1 * u.dimensionless, 1 * u.m**2/u.s, Roughness=1 * u.m, PipeRough=1 * u.m, OpenChannel=True),
lambda: pc.headloss_rect(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 4 * u.m, 1 * u.dimensionless, 1 * u.m**2/u.s, 1 * u.m, OpenChannel=True, openchannel=True))
for i in error_checks:
with self.subTest(i=i):
self.assertRaises(TypeError, i)
warning_checks = (lambda: pc.headloss_rect(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 4 * u.m, 1 * u.dimensionless, 1 * u.m**2/u.s, PipeRough=1 * u.m, OpenChannel=True),
lambda: pc.headloss_rect(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 4 * u.m, 1 * u.dimensionless, 1 * u.m**2/u.s, PipeRough=1 * u.m, openchannel=True),
lambda: pc.headloss_rect(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 4 * u.m, 1 * u.dimensionless, 1 * u.m**2/u.s, 1 * u.m, openchannel=True))
for i in warning_checks:
with self.subTest(i=i):
self.assertWarns(UserWarning, i)
def test_headloss_fric_general(self):
self.assertWarns(UserWarning, pc.headloss_fric_general, *(1 * u.m**2, 1 * u.m, 1 * u.m/u.s, 1 * u.m, 1 * u.m**2/u.s, 1 * u.m))
def test_headloss_major_channel(self):
"""headloss_major_channel should return known result for known inputs."""
checks = (([1 * u.m**2, 1 * u.m, 1 * u.m/u.s, 1 * u.m, 1 * u.m**2/u.s, 1 * u.m], 0.20394324259558566 * u.m),
([25 * u.m**2, 4 * u.m, 0.6 * u.m/u.s, 2 * u.m, 1 * u.m**2/u.s, 1 * u.m], 0.006265136412536391 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.headloss_major_channel(*i[0]), i[1])
def test_headloss_major_channel_range(self):
"""headloss_major_channel should raise an error when Length <= 0."""
checks = ([1 * u.m**2, 1 * u.m, 1 * u.m/u.s, 0 * u.m, 1 * u.m**2/u.s, 1 * u.m],
[15 * u.m**2, 1 * u.m, 1 * u.m/u.s, -1 * u.m, 1 * u.m**2/u.s, 1 * u.m])
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.headloss_major_channel, *i)
def test_headloss_exp_general(self):
self.assertWarns(UserWarning, pc.headloss_exp_general, *(0.06 * u.m/u.s, 0.02))
def test_headloss_minor_channel(self):
"""headloss_minor_channel should return known result for known input."""
self.assertAlmostEqualQuantity(pc.headloss_minor_channel(0.06 * u.m/u.s, 0.02),
3.670978366720542e-06 * u.m)
def test_headloss_minor_channel_range(self):
"""headloss_minor_channel should raise errors if inputs are out of bounds."""
checks = ((0 * u.m/u.s, 1), (1 * u.m/u.s, -1 * u.dimensionless))
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.headloss_minor_channel, *i)
def test_headloss_gen(self):
self.assertWarns(UserWarning, pc.headloss_gen, *(36 * u.m**2, 0.1 * u.m/u.s, 4 * u.m, 6 * u.m, 0.02, 0.86 * u.m**2/u.s, 0.0045 * u.m))
def test_headloss_channel(self):
"""headloss_channel should return known value for known inputs."""
checks = (([36 * u.m**2, 0.1 * u.m/u.s, 4 * u.m, 6 * u.m, 0.02, 0.86 * u.m**2/u.s, 0.0045 * u.m], 0.0013093911519979546 * u.m),
([49 * u.m**2, 2.4 * u.m/u.s, 12 * u.m, 3 * u.m, 2 * u.dimensionless, 4 * u.m**2/u.s, 0.6 * u.m], 0.9396236839032805 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.headloss_channel(*i[0]), i[1])
def test_headloss_manifold(self):
"""headloss_manifold should return known value for known input."""
checks = (([0.12 * u.m**3/u.s, 0.4 * u.m, 6 * u.m, 0.8, 0.75 * u.m**2/u.s, 0.0003 * u.m, 5], 38.57715300752375 * u.m),
([2 * u.m**3/u.s, 6 * u.m, 40 * u.m, 5, 1.1 * u.m**2/u.s, 0.04 * u.m, 6], 0.11938889890999548 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.headloss_manifold(*i[0]), i[1])
def test_headloss_manifold_range(self):
"""headloss_manifold should object if NumOutlets is not a positive int."""
failChecks = ((1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1, 1 * u.m**2/u.s, 1 * u.m, -1),
(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1, 1 * u.m**2/u.s, 1 * u.m, 0),
(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1, 1 * u.m**2/u.s, 1 * u.m, 0.1))
passchecks = ((1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1, 1 * u.m**2/u.s, 1 * u.m, 1.0),
(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1, 1 * u.m**2/u.s, 1 * u.m, 47))
for i in failChecks:
with self.subTest(i=i):
self.assertRaises((ValueError, TypeError), pc.headloss_manifold, *i)
for i in passchecks:
with self.subTest(i=i):
pc.headloss_manifold(*i)
def test_headloss_manifold_warning(self):
"""headloss_manifold should raise warnings when passed deprecated parameters"""
error_checks = (lambda: pc.headloss_manifold(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1, 1 * u.m**2/u.s, Roughness=1 * u.m, NumOutlets=1, PipeRough=1 * u.m),
lambda: pc.headloss_manifold(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1, 1 * u.m**2/u.s, NumOutlets=1),
lambda: pc.headloss_manifold(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1, 1 * u.m**2/u.s, Roughness=1 * u.m))
for i in error_checks:
with self.subTest(i=i):
self.assertRaises(TypeError, i)
warning_checks = (lambda: pc.headloss_manifold(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1, 1 * u.m**2/u.s, PipeRough=1 * u.m, NumOutlets = 1),)
for i in warning_checks:
with self.subTest(i=i):
self.assertWarns(UserWarning, i)
def test_elbow_minor_loss(self):
self.assertWarns(UserWarning, pc.elbow_minor_loss, *(.1*u.m**3/u.s, 0.1*u.m, 0.5))
def test_headloss_minor_elbow(self):
checks = (([.1*u.m**3/u.s, 0.1*u.m, 0.5], 4.132754147128235 * u.m),
([.4*u.m**3/u.s, 0.3*u.m, 0.2], 0.32653859927926804 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.headloss_minor_elbow(*i[0]), i[1])
|
class HeadlossFuncsTest(QuantityTest):
'''Test the headloss functions.'''
def test_headloss_fric(self):
pass
def test_headloss_major_pipe(self):
'''headloss_major_pipe should return known results with known inputs.'''
pass
def test_headloss_major_pipe_range(self):
'''headloss_major_pipe should raise an error if Length <= 0.'''
pass
def test_headloss_exp(self):
pass
def test_headloss_minor_pipe(self):
'''headloss_minor_pipe should return known results with known input.'''
pass
def test_headloss_minor_pipe_range(self):
'''headloss_minor_pipe should raise errors when inputs are out of bounds.'''
pass
def test_headloss_fric(self):
pass
def test_headloss_pipe(self):
'''headloss_pipe should return known results with known inputs.'''
pass
def test_headloss_fric_rect(self):
pass
def test_headloss_major_rect(self):
'''headloss_major_rect should return known result with known inputs.'''
pass
def test_headloss_major_rect_range(self):
'''headloss_major_rect should raise an error when Length <=0.'''
pass
def test_headloss_exp_rect(self):
pass
def test_headloss_minor_rect(self):
'''headloss_minor_rect should return known result for known input.'''
pass
def test_headloss_minor_rect_range(self):
'''headloss_minor_rect should raise errors when inputs are out of bounds.'''
pass
def test_headloss_rect(self):
'''headloss_rect should return known result for known inputs.'''
pass
def test_headloss_rect_warning(self):
'''headloss_rect should raise warnings when passed deprecated parameters'''
pass
def test_headloss_fric_general(self):
pass
def test_headloss_major_channel(self):
'''headloss_major_channel should return known result for known inputs.'''
pass
def test_headloss_major_channel_range(self):
'''headloss_major_channel should raise an error when Length <= 0.'''
pass
def test_headloss_exp_general(self):
pass
def test_headloss_minor_channel(self):
'''headloss_minor_channel should return known result for known input.'''
pass
def test_headloss_minor_channel_range(self):
'''headloss_minor_channel should raise errors if inputs are out of bounds.'''
pass
def test_headloss_gen(self):
pass
def test_headloss_channel(self):
'''headloss_channel should return known value for known inputs.'''
pass
def test_headloss_manifold(self):
'''headloss_manifold should return known value for known input.'''
pass
def test_headloss_manifold_range(self):
'''headloss_manifold should object if NumOutlets is not a positive int.'''
pass
def test_headloss_manifold_warning(self):
'''headloss_manifold should raise warnings when passed deprecated parameters'''
pass
def test_elbow_minor_loss(self):
pass
def test_headloss_minor_elbow(self):
pass
| 30 | 20 | 6 | 0 | 5 | 1 | 2 | 0.13 | 1 | 3 | 0 | 0 | 29 | 0 | 29 | 102 | 207 | 32 | 155 | 70 | 125 | 20 | 126 | 70 | 96 | 3 | 3 | 2 | 50 |
3,266 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_physchem.py
|
test_physchem.MiscPhysFuncsTest
|
class MiscPhysFuncsTest(QuantityTest):
"""Test the miscellaneous physchem functions."""
def test_height_water_critical(self):
"""height_water_critical should return known value for known inputs."""
self.assertAlmostEqualQuantity(pc.height_water_critical(0.006 * u.m**3/u.s, 1.2 * u.m),
0.013660704939951886 * u.m)
def test_height_water_critical_range(self):
"""height_water_critical should raise errors when inputs are out of bounds."""
checks = ((0 * u.m**3/u.s, 1 * u.m), (1 * u.m**3/u.s, 0 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.height_water_critical, *i)
def test_vel_horizontal(self):
"""vel_horizontal should return known value for known inputs."""
self.assertAlmostEqualQuantity(pc.vel_horizontal(0.03 * u.m), 0.5424016039799292 * u.m/u.s)
def test_vel_horizontal_range(self):
"""vel_horizontzal should raise an errors when input is <= 0."""
self.assertRaises(ValueError, pc.vel_horizontal, 0 * u.m)
def test_pipe_ID(self):
"""pipe_ID should return known value for known input"""
self.assertAlmostEqualQuantity(pc.pipe_ID(0.006 * u.m**3/u.s, 1.2 * u.m),
0.039682379412712764 * u.m)
|
class MiscPhysFuncsTest(QuantityTest):
'''Test the miscellaneous physchem functions.'''
def test_height_water_critical(self):
'''height_water_critical should return known value for known inputs.'''
pass
def test_height_water_critical_range(self):
'''height_water_critical should raise errors when inputs are out of bounds.'''
pass
def test_vel_horizontal(self):
'''vel_horizontal should return known value for known inputs.'''
pass
def test_vel_horizontal_range(self):
'''vel_horizontzal should raise an errors when input is <= 0.'''
pass
def test_pipe_ID(self):
'''pipe_ID should return known value for known input'''
pass
| 6 | 6 | 4 | 0 | 3 | 1 | 1 | 0.38 | 1 | 1 | 0 | 0 | 5 | 0 | 5 | 78 | 26 | 4 | 16 | 8 | 10 | 6 | 14 | 8 | 8 | 2 | 3 | 2 | 6 |
3,267 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_physchem.py
|
test_physchem.OrificeFuncsTest
|
class OrificeFuncsTest(QuantityTest):
"""Test the orifice functions."""
def test_flow_orifice(self):
"""flow_orifice should return known result for known input."""
checks = (([0.4 * u.m, 2 * u.m, 0.46], 0.36204122788069698 * u.m**3/u.s),
([2 * u.m, 0.04 * u.m, 0.2], 0.55652566805118475 * u.m**3/u.s),
([7 * u.m, 0 * u.m, 1 * u.dimensionless], 0 * u.m**3/u.s),
([1.4 * u.m, 0.1 * u.m, 0], 0 * u.m**3/u.s))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.flow_orifice(*i[0]), i[1])
def test_flow_orifice_range(self):
"""flow_orifice should raise errors when inputs are out of bounds."""
checks = ((0 * u.m, 1 * u.m, 1), (1 * u.m, 1 * u.m, 1.1),
(1 * u.m, 1 * u.m, -1))
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.flow_orifice, *i)
def test_flow_orifice_vert(self):
"""flow_orifice_vert should return known values for known inputs."""
checks = (([1 * u.m, 3 * u.m, 0.4], 2.4077258053173911 * u.m**3/u.s),
([0.3 * u.m, 4 * u.m, 0.67], 0.41946278400781861 * u.m**3/u.s),
([2 * u.m, -4 * u.m, 0.2 * u.dimensionless], 0 * u.m**3/u.s))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.flow_orifice_vert(*i[0]), i[1])
def test_flow_orifice_vert_range(self):
"""flow_orifice_vert should raise errors when inputs are out of bounds."""
errorChecks = ((1 * u.m, 1 * u.m, -1), (1 * u.m, 1 * u.m, 2))
errorlessChecks = ((1 * u.m, 1 * u.m, 1), (1 * u.m, 1 * u.m, 0),
(1 * u.m, 1 * u.m, 0.5))
for i in errorChecks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.flow_orifice_vert, *i)
for i in errorlessChecks:
with self.subTest(i=i):
pc.flow_orifice_vert(*i)
def test_head_orifice(self):
"""head_orifice should return known value for known inputs."""
checks = (([1 * u.m, 1, 1 * u.m**3/u.s], 0.08265508294256473 * u.m),
([1.2 * u.m, 0.1, 0.12 * u.m**3/u.s], 0.05739936315455882 * u.m),
([2 * u.m, 0.5 * u.dimensionless, 0.04 * u.m**3/u.s], 3.3062033177025895e-05 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.head_orifice(*i[0]), i[1])
def test_head_orifice_range(self):
"""head_orifice should raise errors when passed invalid inputs."""
failChecks = ((0 * u.m, 1, 1 * u.m**3/u.s),
(1 * u.m, 1, 0 * u.m**3/u.s),
(1 * u.m, -1, 1 * u.m**3/u.s),
(1 * u.m, 2, 1 * u.m**3/u.s))
for i in failChecks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.head_orifice, *i)
self.assertRaises(ZeroDivisionError, pc.head_orifice, *(1 * u.m, 0, 1 * u.m**3/u.s))
def test_area_orifice(self):
"""area_orifice should return known value for known inputs."""
checks = (([3 * u.m, 0.4, 0.06 * u.m**3/u.s], 0.019554886342464974 * u.m**2),
([2 * u.m, 0.1, 0.1 * u.m**3/u.s], 0.15966497839052934 * u.m**2),
([0.5 * u.m, 0.02 * u.dimensionless, 3 * u.m**3/u.s], 47.899493517158803 * u.m**2))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.area_orifice(*i[0]), i[1])
def test_area_orifice_range(self):
"""area_orifice should raise errors when inputs are out of bounds."""
failChecks = ((0 * u.m, 1, 1 * u.m**3/u.s),
(1 * u.m, 1, 0 * u.m**3/u.s),
(1 * u.m, -1, 1 * u.m**3/u.s),
(1 * u.m, 2, 1 * u.m**3/u.s),
(1 * u.m, 0, 1 * u.m**3/u.s))
for i in failChecks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.area_orifice, *i)
def test_num_orifices(self):
"""num_orifices should return known value for known inputs."""
checks = (([0.12 * u.m**3/u.s, 0.04, 0.05 * u.m, 2 * u.m], 1 * u.dimensionless),
([6 * u.m**3/u.s, 0.8, 0.08 * u.m, 1.2 * u.m], 6 * u.dimensionless))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.num_orifices(*i[0]), i[1])
|
class OrificeFuncsTest(QuantityTest):
'''Test the orifice functions.'''
def test_flow_orifice(self):
'''flow_orifice should return known result for known input.'''
pass
def test_flow_orifice_range(self):
'''flow_orifice should raise errors when inputs are out of bounds.'''
pass
def test_flow_orifice_vert(self):
'''flow_orifice_vert should return known values for known inputs.'''
pass
def test_flow_orifice_vert_range(self):
'''flow_orifice_vert should raise errors when inputs are out of bounds.'''
pass
def test_head_orifice(self):
'''head_orifice should return known value for known inputs.'''
pass
def test_head_orifice_range(self):
'''head_orifice should raise errors when passed invalid inputs.'''
pass
def test_area_orifice(self):
'''area_orifice should return known value for known inputs.'''
pass
def test_area_orifice_range(self):
'''area_orifice should raise errors when inputs are out of bounds.'''
pass
def test_num_orifices(self):
'''num_orifices should return known value for known inputs.'''
pass
| 10 | 10 | 9 | 0 | 8 | 1 | 2 | 0.14 | 1 | 2 | 0 | 0 | 9 | 0 | 9 | 82 | 88 | 8 | 70 | 29 | 60 | 10 | 51 | 29 | 41 | 3 | 3 | 2 | 19 |
3,268 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_physchem.py
|
test_physchem.PorousMediaFuncsTest
|
class PorousMediaFuncsTest(QuantityTest):
def test_headloss_kozeny(self):
"""headloss_kozeny should raise an error when the user tries to use the function."""
with self.assertRaises(DeprecatedFunctionError):
pc.headloss_kozeny(1 * u.m, 1.4 * u.m, 0.5 * u.m/u.s, 0.625, 0.8 * u.m**2/u.s)
# self.assertRaises(DeprecatedFunctionError, pc.headloss_kozeny(1 * u.m, 1.4 * u.m, 0.5 * u.m/u.s, 0.625, 0.8 * u.m**2/u.s))
# def test_headloss_kozeny(self):
# """headloss_kozeny should return known value for known input."""
# self.assertAlmostEqualQuantity(pc.headloss_kozeny(1 * u.m, 1.4 * u.m, 0.5 * u.m/u.s, 0.625, 0.8 * u.m**2/u.s),
# 2.1576362645214617 * u.m)
# def test_headloss_kozeny_range(self):
# """headloss_kozeny should raise errors when inputs are out of bounds."""
# checks = ((0 * u.m, 1 * u.m, 1 * u.m/u.s, 1, 1 * u.m**2/u.s),
# (1 * u.m, 0 * u.m, 1 * u.m/u.s, 1, 1 * u.m**2/u.s),
# (1 * u.m, 1 * u.m, 0 * u.m/u.s, 1, 1 * u.m**2/u.s),
# (1 * u.m, 1 * u.m, 1 * u.m/u.s, 1, 0 * u.m**2/u.s),
# (1 * u.m, 1 * u.m, 1 * u.m/u.s, -1, 1 * u.m**2/u.s),
# (1 * u.m, 1 * u.m, 1 * u.m/u.s, 2, 1 * u.m**2/u.s))
# for i in checks:
# with self.subTest(i=i):
# self.assertRaises(ValueError, pc.headloss_kozeny, *i)
def test_re_ergun(self):
self.assertAlmostEqualQuantity(pc.re_ergun(0.1 * u.m/u.s, 10**-3 * u.m, 298 * u.degK, 0.2),
139.49692604 * u.dimensionless)
def test_re_ergun_range(self):
checks = ((0 * u.m/u.s, 1 * u.m, 1 * u.degK, .5),
(1 * u.m/u.s, 0 * u.m, 1 * u.degK, .5),
(1 * u.m/u.s, 1 * u.m, -1 * u.degK, .5 * u.dimensionless),
(1 * u.m/u.s, 1 * u.m, 1 * u.degK, 1 * u.dimensionless))
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.re_ergun, *i)
def test_fric_ergun(self):
self.assertAlmostEqualQuantity(pc.fric_ergun(0.1 * u.m/u.s, 10**-3 * u.m, 298 * u.degK, 0.2),
5.6505850237 * u.dimensionless)
def test_headloss_ergun(self):
self.assertAlmostEqualQuantity(pc.headloss_ergun(0.1 * u.m/u.s, 10**-3 * u.m, 298 * u.degK, 0.2, 4 * u.m),
1152.39863230 * u.m)
def test_g_cs_ergun(self):
self.assertAlmostEqualQuantity(pc.g_cs_ergun(0.1 * u.m/u.s, 10**-3 * u.m, 298 * u.degK, 0.2),
39704.892422*u.Hz, 5)
|
class PorousMediaFuncsTest(QuantityTest):
def test_headloss_kozeny(self):
'''headloss_kozeny should raise an error when the user tries to use the function.'''
pass
def test_re_ergun(self):
pass
def test_re_ergun_range(self):
pass
def test_fric_ergun(self):
pass
def test_headloss_ergun(self):
pass
def test_g_cs_ergun(self):
pass
| 7 | 1 | 4 | 0 | 4 | 0 | 1 | 0.71 | 1 | 2 | 1 | 0 | 6 | 0 | 6 | 79 | 46 | 5 | 24 | 9 | 17 | 17 | 17 | 9 | 10 | 2 | 3 | 2 | 7 |
3,269 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/research/test_stock_qc.py
|
tests.research.test_stock_qc.TestStockQC
|
class TestStockQC(unittest.TestCase):
def assertAlmostEqualQuantity(self, first, second, places=7):
self.assertAlmostEqual(first.magnitude, second.magnitude, places)
self.assertAlmostEqual(first.units, second.units, places)
def test_init(self):
self.assertEqual(1*u.mL/u.s, C_reactor.Q_sys())
self.assertEqual(2*u.mg/u.L, C_reactor.C_sys())
self.assertEqual(0.4*u.mL/u.s, C_reactor.Q_stock())
self.assertEqual(4.9*u.mL/u.s, Q_reactor.Q_sys())
self.assertEqual(3.6*u.mg/u.L, Q_reactor.C_sys())
self.assertEqual(50*u.mg/u.L, Q_reactor.C_stock())
def test_C_Stock(self):
self.assertAlmostEqualQuantity(5.0*u.mg/u.L, C_reactor.C_stock())
def test_Q_Stock(self):
self.assertAlmostEqualQuantity(0.3528*u.mL/u.s, Q_reactor.Q_stock())
def test_rpm(self):
self.assertAlmostEqualQuantity(480*u.rev/u.min, C_reactor.rpm(0.05*u.mL/u.rev))
self.assertAlmostEqualQuantity(88.2*u.rev/u.min, Q_reactor.rpm(0.24*u.mL/u.rev))
def test_T_stock(self):
self.assertAlmostEqualQuantity(3.4722222222222222*u.hr, C_reactor.T_stock(5*u.L))
self.assertAlmostEqualQuantity(24.722852103804485*u.hr, Q_reactor.T_stock(31.4*u.L))
def test_M_stock(self):
self.assertAlmostEqualQuantity(25.0*u.mg, C_reactor.M_stock(5*u.L))
self.assertAlmostEqualQuantity(1570.0*u.mg, Q_reactor.M_stock(31.4*u.L))
def test_V_super_stock(self):
self.assertAlmostEqualQuantity(0.00035714285714285714*u.L,
C_reactor.V_super_stock(5*u.L, 70*u.g/u.L))
self.assertAlmostEqualQuantity(0.028035714285714285*u.L,
Q_reactor.V_super_stock(31.4*u.L, 56*u.g/u.L))
def test_dilution_factor(self):
self.assertEqual(7.142857142857142e-05*u.dimensionless, C_reactor.dilution_factor(70*u.g/u.L))
self.assertEqual(0.0008928571428571429*u.dimensionless, Q_reactor.dilution_factor(56*u.g/u.L))
|
class TestStockQC(unittest.TestCase):
def assertAlmostEqualQuantity(self, first, second, places=7):
pass
def test_init(self):
pass
def test_C_Stock(self):
pass
def test_Q_Stock(self):
pass
def test_rpm(self):
pass
def test_T_stock(self):
pass
def test_M_stock(self):
pass
def test_V_super_stock(self):
pass
def test_dilution_factor(self):
pass
| 10 | 0 | 4 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 9 | 0 | 9 | 81 | 42 | 10 | 32 | 10 | 22 | 0 | 30 | 10 | 20 | 1 | 2 | 0 | 9 |
3,270 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/research/test_peristaltic_pump.py
|
tests.research.test_peristaltic_pump.TestTubeSizing
|
class TestTubeSizing(unittest.TestCase):
def assertAlmostEqualQuantity(self, first, second, places=7):
self.assertAlmostEqual(first.magnitude, second.magnitude, places)
self.assertAlmostEqual(first.units, second.units, places)
def test_vol_per_rev_3_stop(self):
self.assertAlmostEqualQuantity(0.0013286183895203283*u.mL/u.rev, pp.vol_per_rev_3_stop(color="orange-black"))
self.assertAlmostEqualQuantity(0.14884596727278449*u.mL/u.rev, pp.vol_per_rev_3_stop(color="yellow-blue"))
self.assertAlmostEqualQuantity(0.0031160704169596186*u.mL/u.rev, pp.vol_per_rev_3_stop(inner_diameter=.20*u.mm))
self.assertAlmostEqualQuantity(0.4005495805189351*u.mL/u.rev, pp.vol_per_rev_3_stop(inner_diameter=2.79*u.mm))
def test_ID_colored_tube(self):
self.assertEqual(1.52*u.mm, pp.ID_colored_tube("yellow-blue"))
self.assertEqual(0.51*u.mm, pp.ID_colored_tube("orange-yellow"))
self.assertEqual(2.79*u.mm, pp.ID_colored_tube("purple-white"))
def test_vol_per_rev_LS(self):
self.assertEqual(0.06*u.mL/u.rev, pp.vol_per_rev_LS(13))
self.assertEqual(1.6*u.mL/u.rev, pp.vol_per_rev_LS(15))
self.assertEqual(3.8*u.mL/u.rev, pp.vol_per_rev_LS(18))
self.assertEqual(4.8*u.mL/u.rev, pp.vol_per_rev_LS(36))
def test_flow_rate(self):
self.assertAlmostEqualQuantity(0.25*u.mL/u.s, pp.flow_rate(3*u.mL/u.rev, 5*u.rev/u.min))
self.assertAlmostEqualQuantity(0.016666666666666666*u.mL/u.s, pp.flow_rate(.04*u.mL/u.rev, 25*u.rev/u.min))
self.assertAlmostEqualQuantity(0.01*u.mL/u.s, pp.flow_rate(.001*u.mL/u.rev, 600*u.rev/u.min))
|
class TestTubeSizing(unittest.TestCase):
def assertAlmostEqualQuantity(self, first, second, places=7):
pass
def test_vol_per_rev_3_stop(self):
pass
def test_ID_colored_tube(self):
pass
def test_vol_per_rev_LS(self):
pass
def test_flow_rate(self):
pass
| 6 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 5 | 0 | 5 | 77 | 27 | 5 | 22 | 6 | 16 | 0 | 22 | 6 | 16 | 1 | 2 | 0 | 5 |
3,271 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/research/test_floc_model.py
|
tests.research.test_floc_model.TestVelocityGradient
|
class TestVelocityGradient(QuantityTest):
def test_g_straight(self):
self.assertAlmostEqualQuantity(fm.g_straight(1*u.mL/u.s, 0.025*u.m),
0.43459910/u.s)
def test_reynolds_rapid_mix(self):
self.assertAlmostEqualQuantity(fm.reynolds_rapid_mix(1*u.mL/u.s, 0.025*u.m, 298*u.degK),
56.83616083*u.dimensionless)
def test_dean_number(self):
self.assertAlmostEqualQuantity(fm.dean_number(1*u.mL/u.s, 0.025*u.m, 0.1*u.m, 298*u.degK),
20.09461737*u.dimensionless)
def test_g_coil(self):
self.assertAlmostEqualQuantity(fm.g_coil(1*u.mL/u.s, 0.025*u.m, 0.1*u.m, 298*u.degK),
0.45480492/u.s)
def test_time_res_tube(self):
self.assertAlmostEqualQuantity(fm.time_res_tube(0.025*u.m, 2*u.m, 1*u.mL/u.s),
981.74770424*u.s)
def test_g_time_res(self):
self.assertAlmostEqualQuantity(fm.g_time_res(1*u.mL/u.s, 0.025*u.m, 0.1*u.m, 2*u.m, 298*u.degK),
446.50368346*u.dimensionless)
|
class TestVelocityGradient(QuantityTest):
def test_g_straight(self):
pass
def test_reynolds_rapid_mix(self):
pass
def test_dean_number(self):
pass
def test_g_coil(self):
pass
def test_time_res_tube(self):
pass
def test_g_time_res(self):
pass
| 7 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 6 | 0 | 6 | 79 | 25 | 6 | 19 | 7 | 12 | 0 | 13 | 7 | 6 | 1 | 3 | 0 | 6 |
3,272 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/research/test_floc_model.py
|
tests.research.test_floc_model.TestPFunctions
|
class TestPFunctions(QuantityTest):
def test_p(self):
self.assertAlmostEqual(fm.p(100, 0.1), -3)
def test_invp(self):
self.assertAlmostEqual(fm.invp(-3, 0.1), 100)
|
class TestPFunctions(QuantityTest):
def test_p(self):
pass
def test_invp(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 75 | 7 | 2 | 5 | 3 | 2 | 0 | 5 | 3 | 2 | 1 | 3 | 0 | 2 |
3,273 |
AguaClara/aguaclara
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AguaClara_aguaclara/aguaclara/research/stock_qc.py
|
aguaclara.research.stock_qc.Variable_Q_Stock
|
class Variable_Q_Stock(Stock):
"""A flow reactor with input from a stock of material at an unknown flow
rate.
:Examples:
>>> from aguaclara.research.stock_qc import Variable_Q_Stock
>>> from aguaclara.core.units import u
>>> reactor = Variable_Q_Stock(Q_sys = 1*u.mL/u.s, C_sys = 1.4*u.mg/u.L, C_stock = 7.6*u.mg/u.L)
>>> round(reactor.Q_stock(), 6)
<Quantity(0.184211, 'milliliter / second')>
>>> pump_speed = reactor.rpm(vol_per_rev = .5*u.mL/u.rev).to(u.rev/u.min)
>>> round(pump_speed, 6)
<Quantity(22.105263, 'rev / minute')>
"""
def __init__(self, Q_sys, C_sys, C_stock):
"""Initialize a reactor of unknown material stock flow rate.
:param Q_sys: Flow rate of the system
:type Q_sys: float
:param C_sys: Concentration of the material in the system
:type C_sys: float
:param C_stock: Concentration of the material in the stock
:type C_stock: float
"""
self._Q_sys = Q_sys
self._C_sys = C_sys
self._C_stock = C_stock
def Q_sys(self):
"""Return the flow rate of the system.
:return: Flow rate of the system
:rtype: float
"""
return self._Q_sys
def C_sys(self):
"""Return the concentration of the material in the system.
:return: Concentration of the material in the system
:rtype: float
"""
return self._C_sys
def C_stock(self):
"""Return the concentration of the material in the stock.
:return: Concentration of the material in the stock
:rtype: float
"""
return self._C_stock
def Q_stock(self):
"""Return the required flow rate from the stock of material given
a reactor's desired system flow rate, system concentration, and stock
concentration.
:return: Flow rate from the stock of material
:rtype: float
"""
return self._Q_sys * (self._C_sys / self._C_stock).to(u.dimensionless)
@ut.list_handler()
def rpm(self, vol_per_rev):
"""Return the pump speed required for the reactor's stock of material
given the volume of fluid output per revolution by the stock's pump.
:param vol_per_rev: Volume of fluid pumped per revolution (dependent on pump and tubing)
:type vol_per_rev: float
:return: Pump speed for the material stock, in revolutions per minute
:rtype: float
"""
return Stock.rpm(self, vol_per_rev, self.Q_stock()).to(u.rev/u.min)
@ut.list_handler()
def T_stock(self, V_stock):
"""Return the amount of time at which the stock of materal will be
depleted.
:param V_stock: Volume of the stock of material
:type V_stock: float
:return: Time at which the stock will be depleted
:rtype: float
"""
return Stock.T_stock(self, V_stock, self.Q_stock()).to(u.hr)
@ut.list_handler()
def M_stock(self, V_stock):
"""Return the mass of undiluted material required for the stock
concentration.
:param V_stock: Volume of the stock of material
:type V_stock: float
:return: Mass of undiluted stock material
:rtype: float
"""
return Stock.M_stock(self, V_stock, self._C_stock)
@ut.list_handler()
def V_super_stock(self, V_stock, C_super_stock):
"""Return the volume of super (more concentrated) stock that must be
diluted for the desired stock volume and stock concentration.
:param V_stock: Volume of the stock of material
:type V_stock: float
:param C_super_stock: Concentration of the super stock
:type C_super_stock: float
:return: Volume of super stock to dilute
:rtype: float
"""
return Stock.V_super_stock(self, V_stock, self._C_stock, C_super_stock)
@ut.list_handler()
def dilution_factor(self, C_super_stock):
"""Return the dilution factor of the concentration of material in the
stock relative to the super stock.
:param C_super_stock: Concentration of the super stock
:type C_super_stock: float
:return: dilution factor of stock concentration over super stock concentration (< 1)
:rtype: float
"""
return Stock.dilution_factor(self, self._C_stock, C_super_stock)
|
class Variable_Q_Stock(Stock):
'''A flow reactor with input from a stock of material at an unknown flow
rate.
:Examples:
>>> from aguaclara.research.stock_qc import Variable_Q_Stock
>>> from aguaclara.core.units import u
>>> reactor = Variable_Q_Stock(Q_sys = 1*u.mL/u.s, C_sys = 1.4*u.mg/u.L, C_stock = 7.6*u.mg/u.L)
>>> round(reactor.Q_stock(), 6)
<Quantity(0.184211, 'milliliter / second')>
>>> pump_speed = reactor.rpm(vol_per_rev = .5*u.mL/u.rev).to(u.rev/u.min)
>>> round(pump_speed, 6)
<Quantity(22.105263, 'rev / minute')>
'''
def __init__(self, Q_sys, C_sys, C_stock):
'''Initialize a reactor of unknown material stock flow rate.
:param Q_sys: Flow rate of the system
:type Q_sys: float
:param C_sys: Concentration of the material in the system
:type C_sys: float
:param C_stock: Concentration of the material in the stock
:type C_stock: float
'''
pass
def Q_sys(self):
'''Return the flow rate of the system.
:return: Flow rate of the system
:rtype: float
'''
pass
def C_sys(self):
'''Return the concentration of the material in the system.
:return: Concentration of the material in the system
:rtype: float
'''
pass
def C_stock(self):
'''Return the concentration of the material in the stock.
:return: Concentration of the material in the stock
:rtype: float
'''
pass
def Q_stock(self):
'''Return the required flow rate from the stock of material given
a reactor's desired system flow rate, system concentration, and stock
concentration.
:return: Flow rate from the stock of material
:rtype: float
'''
pass
@ut.list_handler()
def rpm(self, vol_per_rev):
'''Return the pump speed required for the reactor's stock of material
given the volume of fluid output per revolution by the stock's pump.
:param vol_per_rev: Volume of fluid pumped per revolution (dependent on pump and tubing)
:type vol_per_rev: float
:return: Pump speed for the material stock, in revolutions per minute
:rtype: float
'''
pass
@ut.list_handler()
def T_stock(self, V_stock):
'''Return the amount of time at which the stock of materal will be
depleted.
:param V_stock: Volume of the stock of material
:type V_stock: float
:return: Time at which the stock will be depleted
:rtype: float
'''
pass
@ut.list_handler()
def M_stock(self, V_stock):
'''Return the mass of undiluted material required for the stock
concentration.
:param V_stock: Volume of the stock of material
:type V_stock: float
:return: Mass of undiluted stock material
:rtype: float
'''
pass
@ut.list_handler()
def V_super_stock(self, V_stock, C_super_stock):
'''Return the volume of super (more concentrated) stock that must be
diluted for the desired stock volume and stock concentration.
:param V_stock: Volume of the stock of material
:type V_stock: float
:param C_super_stock: Concentration of the super stock
:type C_super_stock: float
:return: Volume of super stock to dilute
:rtype: float
'''
pass
@ut.list_handler()
def dilution_factor(self, C_super_stock):
'''Return the dilution factor of the concentration of material in the
stock relative to the super stock.
:param C_super_stock: Concentration of the super stock
:type C_super_stock: float
:return: dilution factor of stock concentration over super stock concentration (< 1)
:rtype: float
'''
pass
| 16 | 11 | 10 | 2 | 2 | 6 | 1 | 2.68 | 1 | 0 | 0 | 0 | 10 | 3 | 10 | 15 | 130 | 27 | 28 | 19 | 12 | 75 | 23 | 14 | 12 | 1 | 2 | 0 | 10 |
3,274 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/research/test_floc_model.py
|
tests.research.test_floc_model.TestKolmogorovAndViscous
|
class TestKolmogorovAndViscous(QuantityTest):
def test_eta_kolmogorov(self):
self.assertAlmostEqualQuantity(fm.eta_kolmogorov(2*u.W/u.kg, 298*u.degK),
2.44907189e-5*u.m)
def test_lambda_vel(self):
self.assertAlmostEqualQuantity(fm.lambda_vel(2*u.W/u.kg, 298*u.degK),
0.0012245359*u.m)
def test_diam_kolmogorov(self):
self.assertAlmostEqualQuantity(fm.diam_kolmogorov(2*u.W/u.kg, 298*u.degK, 0.5*u.g/u.L, 10*u.g/u.L, fm.PACl, fm.Clay, fm.DIM_FRACTAL),
4.77577893e-6*u.m)
def test_diam_vel(self):
self.assertAlmostEqualQuantity(fm.diam_vel(2*u.W/u.kg, 298*u.degK, 0.5*u.g/u.L, 10*u.g/u.L, fm.PACl, fm.Clay, fm.DIM_FRACTAL),
0.00078540208*u.m, 10)
def test_diam_floc_max(self):
self.assertRaisesRegex(FutureWarning, "diam_floc_max is deprecated and will be removed after Dec 1 2019. The underlying equation is under suspicion.")
def test_ener_dis_diam_floc(self):
self.assertRaisesRegex(FutureWarning, "ener_dis_diam_floc is deprecated and will be removed after Dec 1 2019. The underlying equation is under suspicion.")
|
class TestKolmogorovAndViscous(QuantityTest):
def test_eta_kolmogorov(self):
pass
def test_lambda_vel(self):
pass
def test_diam_kolmogorov(self):
pass
def test_diam_vel(self):
pass
def test_diam_floc_max(self):
pass
def test_ener_dis_diam_floc(self):
pass
| 7 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 6 | 0 | 6 | 79 | 23 | 6 | 17 | 7 | 10 | 0 | 13 | 7 | 6 | 1 | 3 | 0 | 6 |
3,275 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/research/test_floc_model.py
|
tests.research.test_floc_model.TestFunctions
|
class TestFunctions(QuantityTest):
def test_dens_alum_nanocluster(self):
self.assertAlmostEqualQuantity(fm.dens_alum_nanocluster(fm.PACl),
384.44465833*u.kg/u.m**3)
def test_dens_pacl_solution(self):
self.assertAlmostEqualQuantity(fm.dens_pacl_solution(0.5*u.g/u.L, 298*u.degK),
997.84564733*u.kg/u.m**3)
def test_conc_precipitate(self):
self.assertAlmostEqualQuantity(fm.conc_precipitate(0.5*u.g/u.L, fm.PACl),
1.48005698*u.kg/u.m**3)
def test_conc_floc(self):
self.assertAlmostEqualQuantity(fm.conc_floc(0.5*u.g/u.L, 10*u.g/u.L, fm.PACl),
11.48005698*u.kg/u.m**3)
def test_moles_aluminum(self):
self.assertAlmostEqualQuantity(fm.moles_aluminum(0.45*u.g/u.L),
16.66666667*u.mol/u.m**3)
def test_sep_dist_alumimum(self):
self.assertAlmostEqualQuantity(fm.sep_dist_aluminum(0.45*u.g/u.L),
4.63589330e-9 * u.m, 16)
def test_particle_number_concentration(self):
self.assertAlmostEqualQuantity(fm.particle_number_concentration(10*u.g/u.L, fm.Clay) / 10**5,
21011709303102/u.m**3 / 10**5, 0)
def test_sep_dist_clay(self):
self.assertAlmostEqualQuantity(fm.sep_dist_clay(10*u.g/u.L, fm.Clay),
3.62392782e-5 * u.m, 12)
def test_num_nanoclusters(self):
self.assertAlmostEqualQuantity(fm.num_nanoclusters(0.7*u.g/u.L, fm.PACl) / 10**17,
7.95036025e17 / 10**17 / u.m**3)
def test_frac_vol_floc_initial(self):
self.assertAlmostEqualQuantity(fm.frac_vol_floc_initial(0.5*u.g/u.L, 10*u.g/u.L, fm.PACl, fm.Clay),
0.005074162217*u.dimensionless, 10)
|
class TestFunctions(QuantityTest):
def test_dens_alum_nanocluster(self):
pass
def test_dens_pacl_solution(self):
pass
def test_conc_precipitate(self):
pass
def test_conc_floc(self):
pass
def test_moles_aluminum(self):
pass
def test_sep_dist_alumimum(self):
pass
def test_particle_number_concentration(self):
pass
def test_sep_dist_clay(self):
pass
def test_num_nanoclusters(self):
pass
def test_frac_vol_floc_initial(self):
pass
| 11 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 10 | 0 | 10 | 83 | 41 | 10 | 31 | 11 | 20 | 0 | 21 | 11 | 10 | 1 | 3 | 0 | 10 |
3,276 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/research/test_floc_model.py
|
tests.research.test_floc_model.TestFractalFunctions
|
class TestFractalFunctions(QuantityTest):
def diam_fractal(self):
self.assertAlmostEqualQuantity(fm.diam_fractal(fm.DIM_FRACTAL, 5e-5*u.m, 10),
0.00101811321*u.m, 9)
def test_num_coll_reqd(self):
self.assertAlmostEqualQuantity(fm.num_coll_reqd(fm.DIM_FRACTAL, fm.Clay, 0.001*u.m),
16.464387532*u.dimensionless)
def test_sep_dist_floc(self):
self.assertAlmostEqualQuantity(fm.sep_dist_floc(0.5*u.g/u.L, 10*u.g/u.L, fm.PACl, fm.Clay, fm.DIM_FRACTAL, 0.001*u.m),
0.001473672461*u.m, 9)
def test_frac_vol_floc(self):
self.assertAlmostEqualQuantity(fm.frac_vol_floc(0.5*u.g/u.L, 10*u.g/u.L, fm.PACl, fm.DIM_FRACTAL, fm.Clay, 0.001*u.m),
0.1636046786*u.dimensionless)
def test_dens_floc_init(self):
self.assertAlmostEqualQuantity(fm.dens_floc_init(0.5*u.g/u.L, 10*u.g/u.L, fm.PACl, fm.Clay) / 10**3,
2.2624536798e3 / 10**3 * u.kg/u.m**3)
|
class TestFractalFunctions(QuantityTest):
def diam_fractal(self):
pass
def test_num_coll_reqd(self):
pass
def test_sep_dist_floc(self):
pass
def test_frac_vol_floc(self):
pass
def test_dens_floc_init(self):
pass
| 6 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 5 | 0 | 5 | 78 | 21 | 5 | 16 | 6 | 10 | 0 | 11 | 6 | 5 | 1 | 3 | 0 | 5 |
3,277 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/research/test_floc_model.py
|
tests.research.test_floc_model.TestFlocculationModel
|
class TestFlocculationModel(QuantityTest):
def test_ratio_clay_sphere(self):
self.assertAlmostEqualQuantity(fm.ratio_clay_sphere(1.5),
1.164773953*u.dimensionless)
def test_ratio_area_clay_total(self):
self.assertAlmostEqualQuantity(fm.ratio_area_clay_total(10*u.g/u.L, fm.Clay, 0.0254*u.m, 1.5),
0.9598770465*u.dimensionless)
def test_gamma_coag(self):
self.assertAlmostEqualQuantity(fm.gamma_coag(10*u.g/u.L, 0.5*u.g/u.L, fm.PACl, fm.Clay, 0.025*u.m, 1.5),
0.999112596*u.dimensionless, 5)
def test_gamma_humic_acid_to_coag(self):
self.assertAlmostEqualQuantity(fm.gamma_humic_acid_to_coag(0.5*u.g/u.L, 1.5*u.g/u.L, fm.HumicAcid, fm.PACl),
0.2024813861*u.dimensionless)
def test_pacl_term(self):
self.assertAlmostEqualQuantity(fm.pacl_term(0.025*u.m, 10*u.g/u.L, 0.5*u.g/u.L, 1.5*u.g/u.L, fm.HumicAcid, fm.PACl, fm.Clay, 1.5),
0.7968108928*u.dimensionless)
def test_alpha_pacl_clay(self):
self.assertAlmostEqualQuantity(fm.alpha_pacl_clay(0.025*u.m, 10*u.g/u.L, 0.5*u.g/u.L, 1.5*u.g/u.L, fm.HumicAcid, fm.PACl, fm.Clay, 1.5),
0.001414186281*u.dimensionless)
def test_alpha_pacl_pacl(self):
self.assertAlmostEqualQuantity(fm.alpha_pacl_pacl(0.025*u.m, 10*u.g/u.L, 0.5*u.g/u.L, 1.5*u.g/u.L, fm.HumicAcid, fm.PACl, fm.Clay, 1.5),
0.6349075988*u.dimensionless)
def test_alpha_pacl_nat_org_mat(self):
self.assertAlmostEqualQuantity(fm.alpha_pacl_nat_org_mat(0.025*u.m, 10*u.g/u.L, 0.5*u.g/u.L, 1.5*u.g/u.L, fm.HumicAcid, fm.PACl, fm.Clay, 1.5),
0.3223924016*u.dimensionless)
def test_alpha(self):
self.assertAlmostEqualQuantity(fm.alpha(0.025*u.m, 10*u.g/u.L, 0.5*u.g/u.L, 1.5*u.g/u.L, fm.HumicAcid, fm.PACl, fm.Clay, 1.5),
0.9587141867*u.dimensionless)
def test_pc_viscous(self):
self.assertAlmostEqualQuantity(fm.pc_viscous(1*u.W/u.kg, 298*u.degK, 1*u.s, 0.025*u.m, 10*u.g/u.L, 0.5*u.g/u.L, 1.5*u.g/u.L, fm.HumicAcid, fm.PACl, fm.Clay, 1, 1.5),
2.579165715*u.dimensionless)
def test_dens_floc(self):
self.assertAlmostEqualQuantity(fm.dens_floc(0.5*u.g/u.L, 10*u.g/u.L, fm.DIM_FRACTAL, 0.001*u.m, fm.PACl, fm.Clay, 298*u.degK),
1036.3615768605*u.kg/u.m**3)
def test_vel_term_floc(self):
self.assertAlmostEqualQuantity(fm.vel_term_floc(0.5*u.g/u.L, 10*u.g/u.L, fm.PACl, fm.Clay, fm.DIM_FRACTAL, 0.001*u.m, 298*u.degK),
0.01276232413*u.m/u.s)
def test_diam_floc_vel_term(self):
self.assertAlmostEqualQuantity(fm.diam_floc_vel_term(0.5*u.g/u.L, 10*u.g/u.L, fm.PACl, fm.Clay, 2.3, 0.05*u.m/u.s, 298*u.degK),
0.002858806728*u.m, 9)
def test_time_col_laminar(self):
self.assertAlmostEqualQuantity(fm.time_col_laminar(1*u.W/u.kg, 298*u.degK, 0.5*u.g/u.L, 10*u.g/u.L, fm.PACl, fm.Clay, 0.001*u.m, 0.025*u.m, fm.DIM_FRACTAL, 1.5),
0.00065495327*u.s)
def test_time_col_turbulent(self):
self.assertAlmostEqualQuantity(fm.time_col_turbulent(1*u.W/u.kg, 0.5*u.g/u.L, 10*u.g/u.L, fm.PACl, fm.Clay, 0.001*u.m, fm.DIM_FRACTAL),
0.00895198559*u.s)
|
class TestFlocculationModel(QuantityTest):
def test_ratio_clay_sphere(self):
pass
def test_ratio_area_clay_total(self):
pass
def test_gamma_coag(self):
pass
def test_gamma_humic_acid_to_coag(self):
pass
def test_pacl_term(self):
pass
def test_alpha_pacl_clay(self):
pass
def test_alpha_pacl_pacl(self):
pass
def test_alpha_pacl_nat_org_mat(self):
pass
def test_alpha_pacl_clay(self):
pass
def test_pc_viscous(self):
pass
def test_dens_floc(self):
pass
def test_vel_term_floc(self):
pass
def test_diam_floc_vel_term(self):
pass
def test_time_col_laminar(self):
pass
def test_time_col_turbulent(self):
pass
| 16 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 15 | 0 | 15 | 88 | 61 | 15 | 46 | 16 | 30 | 0 | 31 | 16 | 15 | 1 | 3 | 0 | 15 |
3,278 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/research/test_floc_model.py
|
tests.research.test_floc_model.TestMaterials
|
class TestMaterials(QuantityTest):
def test_Material(self):
self.assertEqual(fm.Clay.name, 'Clay')
self.assertEqual(fm.Clay.Diameter, 7 * 10**-6 * u.m)
self.assertEqual(fm.Clay.Density, 2650 * u.kg/u.m**3)
self.assertEqual(fm.Clay.MolecWeight, None)
def test_Chemical(self):
self.assertEqual(fm.PACl.name, 'PACl')
self.assertEqual(fm.PACl.Diameter, 9 * 10 **-8 * u.m)
self.assertEqual(fm.PACl.Density, 1138 * u.kg/u.m**3)
self.assertEqual(fm.PACl.MolecWeight, 1.039 * u.kg/u.mol)
self.assertEqual(fm.PACl.AluminumMPM, 13)
self.assertEqual(fm.PACl.Precip, 'PACl')
self.assertEqual(fm.PACl.PrecipName, 'PACl')
self.assertEqual(fm.PACl.PrecipDiameter, 9 * 10 **-8 * u.m)
self.assertEqual(fm.PACl.PrecipDensity, 1138 * u.kg/u.m**3)
self.assertEqual(fm.PACl.PrecipMolecWeight, 1.039 * u.kg/u.mol)
self.assertEqual(fm.PACl.PrecipAluminumMPM, 13)
self.assertEqual(fm.Alum.name, 'Alum')
self.assertEqual(fm.Alum.Diameter, 7 * 10 **-8 * u.m)
self.assertEqual(fm.Alum.Density, 2420 * u.kg/u.m**3)
self.assertEqual(fm.Alum.MolecWeight, 0.59921 * u.kg/u.mol)
self.assertEqual(fm.Alum.AluminumMPM, 2)
self.assertEqual(fm.Alum.Precip, 'AlOH3')
self.assertEqual(fm.Alum.PrecipName, 'AlOH3')
self.assertEqual(fm.Alum.PrecipDiameter, 7 * 10 **-8 * u.m)
self.assertEqual(fm.Alum.PrecipDensity, 2420 * u.kg/u.m**3)
self.assertEqual(fm.Alum.PrecipMolecWeight, 0.078 * u.kg/u.mol)
self.assertEqual(fm.Alum.PrecipAluminumMPM, 1)
self.assertEqual(fm.HumicAcid.name, 'Humic Acid')
self.assertEqual(fm.HumicAcid.Diameter, 72 * 10**-9 * u.m)
self.assertEqual(fm.HumicAcid.Density, 1780 * u.kg/u.m**3)
self.assertEqual(fm.HumicAcid.MolecWeight, None)
self.assertEqual(fm.HumicAcid.Precip, 'Humic Acid')
self.assertEqual(fm.HumicAcid.AluminumMPM, None)
self.assertEqual(fm.HumicAcid.Precip, 'Humic Acid')
self.assertEqual(fm.HumicAcid.PrecipName, 'Humic Acid')
self.assertEqual(fm.HumicAcid.PrecipDiameter, 72 * 10**-9 * u.m)
self.assertEqual(fm.HumicAcid.PrecipDensity, 1780 * u.kg/u.m**3)
self.assertEqual(fm.HumicAcid.PrecipMolecWeight, None)
self.assertEqual(fm.HumicAcid.PrecipAluminumMPM, None)
|
class TestMaterials(QuantityTest):
def test_Material(self):
pass
def test_Chemical(self):
pass
| 3 | 0 | 21 | 1 | 20 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 75 | 45 | 4 | 41 | 3 | 38 | 0 | 41 | 3 | 38 | 1 | 3 | 0 | 2 |
3,279 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/research/test_ProCoDA_Parser.py
|
tests.research.test_ProCoDA_Parser.TestProCoDAParser
|
class TestProCoDAParser(unittest.TestCase):
def test_column_of_data(self):
'''''
Extract other columns of data and append units.
'''''
path = os.path.join(os.path.dirname(__file__), '.', 'data', 'example datalog.xls')
answer = pp.column_of_data(path, 50, 1, units='mg/L')
answer = np.round(answer, 5)
self.assertSequenceEqual(
answer.tolist(),
np.round(np.array([ 21.61681747, 21.31163216, 20.80215263, 20.46752739,
20.1048584 , 19.7037487 , 19.4194355 , 18.95934677,
18.65832138, 18.24054337, 17.93864632, 17.591259 ,
17.25979805, 16.98148346, 16.60666656, 16.28514862,
15.99366856, 15.72474861, 15.35812187, 15.11634636,
14.75801468, 14.53341103, 14.20829868, 13.94124603,
13.69845104, 13.42016983, 13.17064667, 12.94155121,
12.66110611, 12.36821651, 12.1641016 , 11.91081715,
11.69137764, 11.46448898, 11.2214098 , 11.03143692,
10.78680801, 10.56936836, 10.36802101, 10.17097855,
9.95537758, 9.78312111, 9.55150509, 9.3843832 ,
9.21883678, 9.03395939, 8.85475636, 8.68857765,
8.47574997, 8.33256149, 8.13628197, 7.96697569,
7.80458403, 7.68562984, 7.4511261 , 7.34629679,
7.17365456, 7.03930044, 6.88661861, 6.73307562,
6.60730886, 6.45987988, 6.30656338, 6.18089199,
6.05378485, 5.90268421, 5.81327915, 5.68042564,
5.57657337, 5.40122986, 5.33153057, 5.19660377,
5.09033108, 4.96228552, 4.85437012, 4.76652002,
4.66415834, 4.54592991, 4.43500376, 4.34614754,
4.24292231, 4.16423607, 4.06328297, 3.96581864,
3.88231015, 3.7828486 , 3.74253488, 3.62953901,
3.53508115, 3.46755266, 3.36818004, 3.30672598,
3.22161722, 3.13899183, 3.08345532, 2.98398542,
2.94956589, 2.8504107 , 2.79215455, 2.72924852,
2.66635823, 2.60831141, 2.53093195, 2.47217631,
2.42190933, 2.36228228, 2.30094266, 2.24602866,
2.19216943, 2.14143515, 2.10641694, 2.07170939,
2.04412961, 2.0158174 , 2.00059986, 1.98546684,
1.97646523, 1.96455812, 1.95887971, 1.94987118])*u('mg/L'), 5).tolist()
)
path = os.path.join(os.path.dirname(__file__), '.', 'data', 'example datalog.xls')
answer = pp.column_of_data(path, 50, "red dye (mg/L)", units='mg/L')
answer = np.round(answer, 5)
self.assertSequenceEqual(
answer.tolist(),
np.round(np.array([ 21.61681747, 21.31163216, 20.80215263, 20.46752739,
20.1048584 , 19.7037487 , 19.4194355 , 18.95934677,
18.65832138, 18.24054337, 17.93864632, 17.591259 ,
17.25979805, 16.98148346, 16.60666656, 16.28514862,
15.99366856, 15.72474861, 15.35812187, 15.11634636,
14.75801468, 14.53341103, 14.20829868, 13.94124603,
13.69845104, 13.42016983, 13.17064667, 12.94155121,
12.66110611, 12.36821651, 12.1641016 , 11.91081715,
11.69137764, 11.46448898, 11.2214098 , 11.03143692,
10.78680801, 10.56936836, 10.36802101, 10.17097855,
9.95537758, 9.78312111, 9.55150509, 9.3843832 ,
9.21883678, 9.03395939, 8.85475636, 8.68857765,
8.47574997, 8.33256149, 8.13628197, 7.96697569,
7.80458403, 7.68562984, 7.4511261 , 7.34629679,
7.17365456, 7.03930044, 6.88661861, 6.73307562,
6.60730886, 6.45987988, 6.30656338, 6.18089199,
6.05378485, 5.90268421, 5.81327915, 5.68042564,
5.57657337, 5.40122986, 5.33153057, 5.19660377,
5.09033108, 4.96228552, 4.85437012, 4.76652002,
4.66415834, 4.54592991, 4.43500376, 4.34614754,
4.24292231, 4.16423607, 4.06328297, 3.96581864,
3.88231015, 3.7828486 , 3.74253488, 3.62953901,
3.53508115, 3.46755266, 3.36818004, 3.30672598,
3.22161722, 3.13899183, 3.08345532, 2.98398542,
2.94956589, 2.8504107 , 2.79215455, 2.72924852,
2.66635823, 2.60831141, 2.53093195, 2.47217631,
2.42190933, 2.36228228, 2.30094266, 2.24602866,
2.19216943, 2.14143515, 2.10641694, 2.07170939,
2.04412961, 2.0158174 , 2.00059986, 1.98546684,
1.97646523, 1.96455812, 1.95887971, 1.94987118])*u('mg/L'), 5).tolist()
)
def test_column_of_time(self):
'''''
Extract the time column from a data file.
'''''
path = os.path.join(os.path.dirname(__file__), '.', 'data', 'example datalog.xls')
answer = pp.column_of_time(path, 50)
answer = np.round(answer, 5)
self.assertSequenceEqual(
answer.tolist(),
np.round(np.array([0.00000000e+00, 5.78662000e-05, 1.15725500e-04,
1.73586900e-04, 2.31470400e-04, 2.89325100e-04,
3.47199600e-04, 4.05070800e-04, 4.62941200e-04,
5.20805100e-04, 5.78682300e-04, 6.36541000e-04,
6.94405500e-04, 7.52295200e-04, 8.10152600e-04,
8.68025100e-04, 9.25879200e-04, 9.83766900e-04,
1.04163170e-03, 1.09949610e-03, 1.15736260e-03,
1.21522990e-03, 1.27310590e-03, 1.33096560e-03,
1.38884810e-03, 1.44671260e-03, 1.50456890e-03,
1.56244910e-03, 1.62031940e-03, 1.67819090e-03,
1.73605480e-03, 1.79390590e-03, 1.85178640e-03,
1.90965780e-03, 1.96752080e-03, 2.02538760e-03,
2.08325540e-03, 2.14113380e-03, 2.19899280e-03,
2.25686180e-03, 2.31473400e-03, 2.37261100e-03,
2.43048170e-03, 2.48834570e-03, 2.54620210e-03,
2.60408890e-03, 2.66194550e-03, 2.71981170e-03,
2.77768240e-03, 2.83556180e-03, 2.89342620e-03,
2.95130110e-03, 3.00916580e-03, 3.06704400e-03,
3.12490300e-03, 3.18278490e-03, 3.24064920e-03,
3.29852180e-03, 3.35638230e-03, 3.41425150e-03,
3.47212870e-03, 3.52999870e-03, 3.58786830e-03,
3.64572740e-03, 3.70359810e-03, 3.76146930e-03,
3.81933520e-03, 3.87721010e-03, 3.93506860e-03,
3.99295440e-03, 4.05082240e-03, 4.10868470e-03,
4.16654890e-03, 4.22442890e-03, 4.28230160e-03,
4.34016650e-03, 4.39804130e-03, 4.45591720e-03,
4.51377060e-03, 4.57164920e-03, 4.62952340e-03,
4.68739510e-03, 4.74524320e-03, 4.80312930e-03,
4.86098350e-03, 4.91887450e-03, 4.97673430e-03,
5.03459310e-03, 5.09248050e-03, 5.15033640e-03,
5.20820950e-03, 5.26607440e-03, 5.32394690e-03,
5.38181660e-03, 5.43967960e-03, 5.49755470e-03,
5.55543130e-03, 5.61330110e-03, 5.67117330e-03,
5.72903190e-03, 5.78690100e-03, 5.84477570e-03,
5.90264880e-03, 5.96051240e-03, 6.01837960e-03,
6.07625150e-03, 6.13413050e-03, 6.19199110e-03,
6.24987260e-03, 6.30772900e-03, 6.36560880e-03,
6.42346920e-03, 6.48135320e-03, 6.53921020e-03,
6.59709090e-03, 6.65494290e-03, 6.71281870e-03,
6.77069570e-03, 6.82855640e-03, 6.88642010e-03])*u.day, 5).tolist()
)
answer = pp.column_of_time(path, 50, end=60, units='hr')
answer = np.round(answer, 5)
self.assertSequenceEqual(
answer.tolist(),
np.round(np.array([0.00000000e+00, 5.78662000e-05, 1.15725500e-04,
1.73586900e-04, 2.31470400e-04, 2.89325100e-04,
3.47199600e-04, 4.05070800e-04, 4.62941200e-04,
5.20805100e-04])*24*u.hr, 5).tolist()
)
def test_notes(self):
'''''
Test function that extracts meta information from data file.
'''''
path = os.path.join(os.path.dirname(__file__), '.', 'data', 'example datalog.xls')
answer = pp.notes(path)['Day fraction since midnight on ']
x = pd.DataFrame(index=[1, 29, 35],
columns=['Day fraction since midnight on ', 'red dye (mg/L)', 'Run Pump ()', 'Pump ()'])
x.iloc[0][0] = 'Start'
x.iloc[1][0] = 'Start'
x.iloc[2][0] = '30 mg/L'
self.assertSequenceEqual(
answer.tolist(),
x['Day fraction since midnight on '].tolist())
def test_remove_notes(self):
'''
Return a DataFrame without any lines that originally contained text
'''
path = os.path.join(os.path.dirname(__file__), '.', 'data')
output = pp.remove_notes(pd.read_csv(path + '/example datalog.xls', delimiter='\t'))
self.assertSequenceEqual(np.round(pd.to_numeric(output.iloc[:, 0]), 5).tolist(), np.round(np.array(
[0.6842773323, 0.6843351954, 0.6843930789, 0.6844509555, 0.6845088278,
0.6845666989, 0.6846245615, 0.6846824172, 0.6847402968, 0.6847981752,
0.6848560403, 0.6849139126, 0.6849717883, 0.6850296562, 0.6850875147,
0.6851453919, 0.6852032725, 0.6852611229, 0.6853190069, 0.6853768753,
0.6854347496, 0.6854926132, 0.6855504820, 0.6856083520, 0.6856662182,
0.6857240844, 0.6857819618, 0.6858398270, 0.6858977139, 0.6859555700,
0.6860134505, 0.6860713232, 0.6861291842, 0.6861870457, 0.6862449249,
0.6863027915, 0.6863606668, 0.6864185391, 0.6864764071, 0.6865342703,
0.6865921393, 0.6866500041, 0.6867078679, 0.6867657506, 0.6868236041,
0.6868814757, 0.6869393510, 0.6869972210, 0.6870550872, 0.6871129465,
0.6871708079, 0.6872286914, 0.6872865461, 0.6873444206, 0.6874022918,
0.6874601622, 0.6875180261, 0.6875759033, 0.6876337620, 0.6876916265,
0.6877495162, 0.6878073736, 0.6878652461, 0.6879231002, 0.6879809879,
0.6880388527, 0.6880967171, 0.6881545836, 0.6882124509, 0.6882703269,
0.6883281866, 0.6883860691, 0.6884439336, 0.6885017899, 0.6885596701,
0.6886175404, 0.6886754119, 0.6887332758, 0.6887911269, 0.6888490074,
0.6889068788, 0.6889647418, 0.6890226086, 0.6890804764, 0.6891383548,
0.6891962138, 0.6892540828, 0.6893119550, 0.6893698320, 0.6894277027,
0.6894855667, 0.6895434231, 0.6896013099, 0.6896591665, 0.6897170327,
0.6897749034, 0.6898327828, 0.6898906472, 0.6899485221, 0.6900063868,
0.6900642650, 0.6901221240, 0.6901800059, 0.6902378702, 0.6902957428,
0.6903536033, 0.6904114725, 0.6904693497, 0.6905272197, 0.6905850893,
0.6906429484, 0.6907008191, 0.6907586903, 0.6908165562, 0.6908744311,
0.6909322896, 0.6909901754, 0.6910480434, 0.6911059057, 0.6911637699,
0.6912216499, 0.6912795226, 0.6913373875, 0.6913952623, 0.6914531382,
0.6915109916, 0.6915688702, 0.6916267444, 0.6916846161, 0.6917424642,
0.6918003503, 0.6918582045, 0.6919160955, 0.6919739553, 0.6920318141,
0.6920897015, 0.6921475574, 0.6922054305, 0.6922632954, 0.6923211679,
0.6923790376, 0.6924369006, 0.6924947757, 0.6925526523, 0.6926105221,
0.6926683943, 0.6927262529, 0.6927841220, 0.6928419967, 0.6928998698,
0.6929577334, 0.6930156006, 0.6930734725, 0.6931313515, 0.6931892121,
0.6932470936, 0.6933049500, 0.6933628298, 0.6934206902, 0.6934785742,
0.6935364312, 0.6935943119, 0.6936521639, 0.6937100397, 0.6937679167,
0.6938257774, 0.6938836411]), 5).tolist())
def test_get_data_by_time(self):
'''
Extract column(s) of data between given starting and ending days and times
'''
path = os.path.join(os.path.dirname(__file__), '.', 'data')
data_day1 = pd.read_csv(path + '/datalog_6-14-2018.xls', delimiter='\t')
data_day1 = np.round([pd.to_numeric(data_day1.iloc[:, 0]), pd.to_numeric(data_day1.iloc[:, 4])], 5)
data_day1 = [data_day1[0].tolist(), data_day1[1].tolist()]
data_day2 = pd.read_csv(path + '/datalog_6-15-2018.xls', delimiter='\t')
data_day2 = np.round([pd.to_numeric(data_day2.iloc[:, 0]), pd.to_numeric(data_day2.iloc[:, 4])], 5)
data_day2 = [data_day2[0].tolist(), data_day2[1].tolist()]
data_day2[0][0] = 0 # to remove scientific notation "e-"
# SINGLE COLUMN, ONE DAY
output = pp.get_data_by_time(path=path, columns=0, dates="6-14-2018", start_time="12:20",
end_time="13:00", extension=".xls")
self.assertSequenceEqual(np.round(output, 5).tolist(), data_day1[0][1041:1282])
# SINGLE COLUMN, TWO DAYS
output = pp.get_data_by_time(path=path, columns=0, dates=["6-14-2018", "6-15-2018"],
start_time="12:20", end_time="10:50", extension=".xls")
time_column = data_day1[0][1041:] + np.round(np.array(data_day2[0][:3901])+1, 5).tolist()
self.assertSequenceEqual(np.round(output, 5).tolist(), time_column)
# MULTI COLUMN, ONE DAY
output = pp.get_data_by_time(path=path, columns=[0, 4], dates=["6-14-2018"], start_time="12:20",
end_time="13:00", extension=".xls")
self.assertSequenceEqual(np.round(output[0], 5).tolist(), data_day1[0][1041:1282])
self.assertSequenceEqual(np.round(output[1], 5).tolist(), data_day1[1][1041:1282])
# MULTI COLUMN, TWO DAYS
output = pp.get_data_by_time(path=path, columns=[0, 4], dates=["6-14-2018", "6-15-2018"],
start_time="12:20", end_time="10:50", extension=".xls")
time_column = data_day1[0][1041:] + np.round(np.array(data_day2[0][:3901])+1, 5).tolist()
self.assertSequenceEqual(np.round(output[0], 5).tolist(), time_column)
self.assertSequenceEqual(np.round(output[1], 5).tolist(), data_day1[1][1041:]+data_day2[1][:3901])
# MULTI COLUMN, TWO DAYS, WITH UNITS
output = pp.get_data_by_time(path=path, columns=[0, 4], dates=["6-14-2018", "6-15-2018"],
start_time="12:20", end_time="10:50", extension=".xls", units=['day', 'mg/L'])
time_column = data_day1[0][1041:] + np.round(np.array(data_day2[0][:3901])+1, 5).tolist()
self.assertEqual(output[0].units, u.day)
self.assertSequenceEqual(np.round(output[0].magnitude, 5).tolist(), time_column)
self.assertEqual(output[1].units, u.mg/u.L)
self.assertSequenceEqual(np.round(output[1].magnitude, 5).tolist(), data_day1[1][1041:]+data_day2[1][:3901])
######## WITH ELAPSED TIME ########
start = pp.day_fraction("12:20")
data_day1 = pd.read_csv(path + '/datalog_6-14-2018.xls', delimiter='\t')
data_day1 = [np.round(pd.to_numeric(data_day1.iloc[:, 0]) - start, 5).tolist(),
np.round(pd.to_numeric(data_day1.iloc[:, 4]), 5).tolist()]
data_day2 = pd.read_csv(path + '/datalog_6-15-2018.xls', delimiter='\t')
data_day2.iloc[0,0] = 0 # to remove scientific notation "e-"
data_day2 = [np.round(pd.to_numeric(data_day2.iloc[:, 0]) - start + 1, 5).tolist(),
np.round(pd.to_numeric(data_day2.iloc[:, 4]), 5).tolist()]
# SINGLE COLUMN, ONE DAY
output = pp.get_data_by_time(path=path, columns=0, dates="6-14-2018", start_time="12:20",
end_time="13:00", extension=".xls", elapsed=True)
self.assertSequenceEqual(np.round(output, 5).tolist(), data_day1[0][1041:1282])
# MULTI COLUMN, TWO DAYS
output = pp.get_data_by_time(path=path, columns=[0, 4], dates=["6-14-2018", "6-15-2018"],
start_time="12:20", end_time="10:50", extension=".xls",
elapsed=True)
self.assertSequenceEqual(np.round(output[0], 5).tolist(), data_day1[0][1041:]+data_day2[0][:3901])
self.assertSequenceEqual(np.round(output[1], 5).tolist(), data_day1[1][1041:]+data_day2[1][:3901])
def test_day_fraction(self):
'''
Converts time into a fraction of the day
'''
time = pp.day_fraction(time="12:00")
self.assertEqual(time, 0.5)
def test_data_from_dates(self):
'''
Return a list of DataFrames representing the ProCoDA data files stored in the given path and recorded on the given dates.
'''
path = os.path.join(os.path.dirname(__file__), '.', 'data')
dataFromPath = pd.read_csv(path + '/datalog_6-15-2018.xls', delimiter='\t')
getDataFromDates = pp.data_from_dates(path=path, dates='6-15-2018', extension=".xls")[0]
self.assertTrue(getDataFromDates.equals(dataFromPath))
def test_column_start_to_end(self):
'''
Return entries in column from starting index in first DataFrame to ending index in last DataFrame
'''
#One DataFrame
path = os.path.join(os.path.dirname(__file__), '.', 'data')
data_manual1 = pd.read_csv(path + '/datalog_6-14-2018.xls', delimiter='\t')
getColData1 = pp.column_start_to_end(data=[data_manual1], column=1, start_idx=2, end_idx=7)
compareColData1 = [-4.34825945, -2.3821919, -2.57200098, -2.40549088,
-1.00214481]
self.assertSequenceEqual(getColData1, compareColData1)
#Three DataFrames
data_manual2 = pd.read_csv(path + '/datalog_6-16-2018.xls', delimiter='\t')
data_manual3 = pd.read_csv(path + '/datalog_6-15-2018.xls', delimiter='\t')
getColData2 = pp.column_start_to_end([data_manual1, data_manual2, data_manual3],
column=2, start_idx=5238, end_idx=2)
compareColData2 = [24.26625443, 24.2669487, 24.26613235, 24.26708603,
24.26683617, 24.26708603, 24.26683617]
self.assertSequenceEqual(getColData2, compareColData2)
def test_get_data_by_state(self):
'''
Extract the time column and a data column for each iteration of a state
'''
path = os.path.join(os.path.dirname(__file__), '.', 'data')
# Local path
output = pp.get_data_by_state(path, dates="6-19-2013", state=1, column=1, extension=".xls") # , "6-20-2013"
datafile = pd.read_csv(path + "/datalog_6-19-2013.xls", delimiter='\t')
time_and_data1 = np.array([pd.to_numeric(datafile.iloc[:, 0]),
np.round(pd.to_numeric(datafile.iloc[:, 1]), 5)])
start_time = time_and_data1[0, 0]
answer = [time_and_data1[:, 98:175], time_and_data1[:, 220:485],
time_and_data1[:, 3039:3304], time_and_data1[:, 5858:6123],
time_and_data1[:, 8677:8942], time_and_data1[:, 11496:11761],
time_and_data1[:, 14315:14580]]
for i in range(len(output)):
output_i = np.round(np.array(output[i]).astype(np.double), 5)
self.assertSequenceEqual([j[0] for j in output_i], [round(j-start_time, 5) for j in answer[i][0]])
self.assertSequenceEqual([j[1] for j in output_i], [j for j in answer[i][1]])
# Acceptable URL
url_acceptable = 'https://raw.githubusercontent.com/monroews/playing/master/ProCoDA_data'
output = pp.get_data_by_state(url_acceptable, dates="11-5-2019", state=1, column=1, extension='.tsv')
answer = pp.get_data_by_state(path, dates="11-5-2019", state=1, column=1, extension='.tsv')
for i in range(len(output)):
self.assertSequenceEqual([round(o, 5) for o in output[i][:,0]], [round(a, 5) for a in answer[i][:,0]])
self.assertSequenceEqual([round(o, 5) for o in output[i][:,1]], [round(a, 5) for a in answer[i][:,1]])
# Github.com URL (blob)
url_github = 'https://github.com/monroews/playing/blob/master/ProCoDA_data'
output = pp.get_data_by_state(url_github, dates="11-5-2019", state=1, column=1, extension='.tsv')
for i in range(len(output)):
self.assertSequenceEqual([round(o, 5) for o in output[i][:,0]], [round(a, 5) for a in answer[i][:,0]])
self.assertSequenceEqual([round(o, 5) for o in output[i][:,1]], [round(a, 5) for a in answer[i][:,1]])
# Github.com URL (tree)
url_github = 'https://github.com/monroews/playing/tree/master/ProCoDA_data'
output = pp.get_data_by_state(url_github, dates="11-5-2019", state=1, column=1, extension='.tsv')
for i in range(len(output)):
self.assertSequenceEqual([round(o, 5) for o in output[i][:,0]], [round(a, 5) for a in answer[i][:,0]])
self.assertSequenceEqual([round(o, 5) for o in output[i][:,1]], [round(a, 5) for a in answer[i][:,1]])
def test_plot_columns(self):
'''
Plot the columns of data given the file located by labels
'''
path = os.path.join(os.path.dirname(__file__), '.', 'data') + '/statelog_6-14-2018.xls'
plt.figure()
pp.plot_columns(path=path, columns=" State ID")
plt.savefig("Image1.png")
plt.figure()
plt.plot([0,1,0,1,2])
plt.savefig("Image2.png")
self.assertEqual(None, compare_images("Image2.png", "Image1.png", 0))
plt.figure()
pp.plot_columns(path=path, columns=" State ID", x_axis=" State ID")
plt.savefig("Image3.png")
plt.figure()
plt.plot([0,1,0,1,2], [0,1,0,1,2])
plt.savefig("Image4.png")
self.assertEqual(None, compare_images("Image4.png", "Image3.png", 0))
plt.figure()
pp.plot_columns(path=path, columns=[" State ID"])
plt.savefig("Image5.png")
self.assertEqual(None, compare_images("Image1.png", "Image5.png", 0))
plt.figure()
pp.plot_columns(path=path, columns=[" State ID"], x_axis=" State ID")
plt.savefig("Image6.png")
self.assertEqual(None, compare_images("Image4.png", "Image6.png", 0))
self.assertRaisesRegex(ValueError, 'columns must be a string or list of strings',
pp.plot_columns, *(path, 9))
os.remove("Image1.png")
os.remove("Image2.png")
os.remove("Image3.png")
os.remove("Image4.png")
os.remove("Image5.png")
os.remove("Image6.png")
def test_iplot_columns(self):
'''
Plot the columns of data given the file located by indices
'''
path = os.path.join(os.path.dirname(__file__), '.', 'data') + '/statelog_6-14-2018.xls'
plt.figure()
pp.iplot_columns(path=path, columns=1)
plt.savefig("Image1.png")
plt.figure()
plt.plot([0,1,0,1,2])
plt.savefig("Image2.png")
self.assertEqual(None, compare_images("Image2.png", "Image1.png", 0))
plt.figure()
pp.iplot_columns(path=path, columns=1, x_axis=1)
plt.savefig("Image3.png")
plt.figure()
plt.plot([0,1,0,1,2], [0,1,0,1,2])
plt.savefig("Image4.png")
self.assertEqual(None, compare_images("Image4.png", "Image3.png", 0))
plt.figure()
pp.iplot_columns(path=path, columns=[1])
plt.savefig("Image5.png")
self.assertEqual(None, compare_images("Image1.png", "Image5.png", 0))
plt.figure()
pp.iplot_columns(path=path, columns=[1], x_axis=1)
plt.savefig("Image6.png")
self.assertEqual(None, compare_images("Image4.png", "Image6.png", 0))
self.assertRaisesRegex(ValueError, 'columns must be an int or a list of ints',
pp.iplot_columns, *(path, ' State ID'))
os.remove("Image1.png")
os.remove("Image2.png")
os.remove("Image3.png")
os.remove("Image4.png")
os.remove("Image5.png")
os.remove("Image6.png")
def test_read_state(self):
path = os.path.join(os.path.dirname(__file__), '.', 'data', '')
output_time, output_data = pp.read_state(["6-19-2013", "6-20-2013"], 1, 28, "mL/s", path, extension=".xls")
df_day1 = pd.read_csv(path + "/datalog_6-19-2013.xls", delimiter='\t')
df_day2 = pd.read_csv(path + "/datalog_6-20-2013.xls", delimiter='\t')
time_day1 = df_day1.iloc[:,0]
data_day1 = df_day1.iloc[:,28]
time_day2 = df_day2.iloc[:,0] + 1
data_day2 = df_day2.iloc[:,28]
answer_time = pd.concat([
time_day1[98:175], time_day1[220:485], time_day1[3039:3304],
time_day1[5858:6123], time_day1[8677:8942], time_day1[11496:11761],
time_day1[14315:14580],
time_day2[1442:1707], time_day2[4261:4526], time_day2[7080:7345],
time_day2[9899:10164], time_day2[12718:12983], time_day2[36572:40549],
time_day2[41660:41694], time_day2[41696:41698]
]) - time_day1.iloc[0]
answer_data = pd.concat([
data_day1[98:175], data_day1[220:485], data_day1[3039:3304],
data_day1[5858:6123], data_day1[8677:8942], data_day1[11496:11761],
data_day1[14315:14580],
data_day2[1442:1707], data_day2[4261:4526], data_day2[7080:7345],
data_day2[9899:10164], data_day2[12718:12983], data_day2[36572:40549],
data_day2[41660:41694], data_day2[41696:41698]
])
self.assertEqual(output_time.units, u.day)
self.assertSequenceEqual(list(output_time.magnitude), list(answer_time))
self.assertEqual(output_data.units, u.mL/u.s)
self.assertSequenceEqual(list(output_data.magnitude), list(answer_data))
def test_average_state(self):
path = os.path.join(os.path.dirname(__file__), '.', 'data', '')
avgs = pp.average_state(["6-19-2013", "6-20-2013"], 1, 28, "mL/s", path,
extension=".xls")
avgs = np.round(avgs, 5)
self.assertSequenceEqual(
avgs.tolist(),
[5.5, 5.5, 5.5, 5.43125, 5.42094, 5.40908, 5.39544, 5.37976, 5.36172,
5.34098, 5.31712, 5.28969, 5.5, 5.5, 5.5]*u.mL/u.s
)
def test_perform_function_on_state(self):
path = os.path.join(os.path.dirname(__file__), '.', 'data', '')
def avg_with_units(lst):
num = np.size(lst)
acc = 0
for i in lst:
acc = i + acc
return acc / num
avgs = pp.perform_function_on_state(avg_with_units,
["6-19-2013", "6-20-2013"], 1, 28,
"mL/s", path, extension=".xls")
avgs = np.round(avgs, 5)
self.assertSequenceEqual(
avgs.tolist(),
[5.5, 5.5, 5.5, 5.43125, 5.42094, 5.40908, 5.39544, 5.37976, 5.36172,
5.34098, 5.31712, 5.28969, 5.5, 5.5, 5.5]*u.mL/u.s
)
def test_read_state_with_metafile(self):
path = os.path.join(os.path.dirname(__file__), '.', 'data', 'Test Meta File.txt')
def avg_with_units(lst):
num = np.size(lst)
acc = 0
for i in lst:
acc = i + acc
return acc / num
ids, answer = pp.read_state_with_metafile(avg_with_units, 1, 28, path, [], ".xls", "mg/L")
self.assertSequenceEqual(["1", "2"], ids.tolist())
self.assertSequenceEqual([5.445427082723495, 5.459751965314751]*u.mg/u.L, answer)
def test_write_calculations_to_csv(self):
path = os.path.join(os.path.dirname(__file__), '.', 'data', 'Test Meta File.txt')
out_path = os.path.join(os.path.dirname(__file__), '.', 'data', 'test_output.txt')
def avg_with_units(lst):
num = np.size(lst)
acc = 0
for i in lst:
acc = i + acc
return acc / num
output = pp.write_calculations_to_csv(avg_with_units, 1, 28, path,
["Average Conc (mg/L)"], out_path,
extension=".xls")
self.assertSequenceEqual(["1", "2"], output['ID'].tolist())
self.assertSequenceEqual(
[5.445427082723495, 5.459751965314751],
output['Average Conc (mg/L)'].tolist())
def test_intersect(self):
#tests one crossing
x = np.array([1,2,3])
y1 = np.array([2,6,8])
y2 = np.array([6,2,3])
output = pp.intersect(x, y1, y2)
expected = (np.array([1.5]), np.array([4]), np.array([1]))
for i in range(len(expected)):
self.assertSequenceEqual(list(expected[i]), list(output[i]))
#tests two crossings
x = np.array([1,2,3,4,5,6])
y1 = np.array([2,6,8,4,1])
y2 = np.array([6,2,3,7,6])
output = pp.intersect(x,y1,y2)
expected = (np.array([1.5, 3.625]), np.array([4, 5.5]), np.array([1, 3]))
for i in range(len(expected)):
self.assertSequenceEqual(list(expected[i]), list(output[i]))
#tests parallel lines
x = np.array([1,2,3,4])
y1 = np.array([3,5,7,9])
y2 = np.array([5,7,9,11])
output = pp.intersect(x,y1,y2)
expected = (np.array([]), np.array([]), np.array([]))
for i in range(len(expected)):
self.assertSequenceEqual(list(expected[i]), list(output[i]))
#tests equal and crossing
x = np.array([-2,-1,0,1,2])
y1 = np.array([2,1,0,-1,-2])
y2 = np.array([-2,-1,0,1,2])
output = pp.intersect(x,y1,y2)
expected = (np.array([-0, -0]), np.array([0, 0]), np.array([2, 3]))
for i in range(len(expected)):
self.assertSequenceEqual(list(expected[i]), list(output[i]))
#tests equal and not crossing
x = np.array([0,1,2,3,4])
y1 = np.array([4,4,4,4,4])
y2 = np.array([3,4,3,0,-5])
output = pp.intersect(x,y1,y2)
expected = (np.array([1, 1]), np.array([4, 4]), np.array([1, 2]))
for i in range(len(expected)):
self.assertSequenceEqual(list(expected[i]), list(output[i]))
|
class TestProCoDAParser(unittest.TestCase):
def test_column_of_data(self):
'''''
Extract other columns of data and append units.
'''
pass
def test_column_of_time(self):
'''''
Extract the time column from a data file.
'''
pass
def test_notes(self):
'''''
Test function that extracts meta information from data file.
'''
pass
def test_remove_notes(self):
'''
Return a DataFrame without any lines that originally contained text
'''
pass
def test_get_data_by_time(self):
'''
Extract column(s) of data between given starting and ending days and times
'''
pass
def test_day_fraction(self):
'''
Converts time into a fraction of the day
'''
pass
def test_data_from_dates(self):
'''
Return a list of DataFrames representing the ProCoDA data files stored in the given path and recorded on the given dates.
'''
pass
def test_column_start_to_end(self):
'''
Return entries in column from starting index in first DataFrame to ending index in last DataFrame
'''
pass
def test_get_data_by_state(self):
'''
Extract the time column and a data column for each iteration of a state
'''
pass
def test_plot_columns(self):
'''
Plot the columns of data given the file located by labels
'''
pass
def test_iplot_columns(self):
'''
Plot the columns of data given the file located by indices
'''
pass
def test_read_state(self):
pass
def test_average_state(self):
pass
def test_perform_function_on_state(self):
pass
def avg_with_units(lst):
pass
def test_read_state_with_metafile(self):
pass
def avg_with_units(lst):
pass
def test_write_calculations_to_csv(self):
pass
def avg_with_units(lst):
pass
def test_intersect(self):
pass
| 21 | 11 | 30 | 3 | 24 | 2 | 2 | 0.1 | 1 | 3 | 0 | 0 | 17 | 0 | 17 | 89 | 604 | 89 | 472 | 94 | 451 | 46 | 269 | 94 | 248 | 6 | 2 | 1 | 32 |
3,280 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/research/test_floc_model.py
|
tests.research.test_floc_model.QuantityTest
|
class QuantityTest(unittest.TestCase):
def assertAlmostEqualQuantity(self, first, second, places=7):
self.assertAlmostEqual(first.magnitude, second.magnitude, places)
self.assertEqual(first.units, second.units, places)
|
class QuantityTest(unittest.TestCase):
def assertAlmostEqualQuantity(self, first, second, places=7):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 7 | 1 | 0 | 1 | 73 | 5 | 1 | 4 | 2 | 2 | 0 | 4 | 2 | 2 | 1 | 2 | 0 | 1 |
3,281 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_physchem.py
|
test_physchem.RadiusFuncsTest
|
class RadiusFuncsTest(QuantityTest):
"""Test the various radius-acquisition functions."""
def test_radius_hydraulic(self):
self.assertWarns(UserWarning, pc.radius_hydraulic, *(10 * u.m, 4 * u.m, False))
def test_radius_hydraulic_rect(self):
"""radius_hydraulic_rect should return known results with known input."""
checks = (([10 * u.m, 4 * u.m, False], 1.4285714285714286 * u.m),
([10 * u.m, 4 * u.m, True], 2.2222222222222223 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.radius_hydraulic_rect(*i[0]), i[1])
def test_radius_hydraulic_range(self):
"""radius_hydraulic should raise errors when inputs are out of bounds."""
checks = (([0 * u.m, 4 * u.m, True], ValueError),
([-1 * u.m, 4 * u.m, True], ValueError),
([1 * u.m, 0 * u.m, True], ValueError),
([10 * u.m, -1 * u.m, True], ValueError),
([10 * u.m, 4 * u.m, 0 * u.m], TypeError),
([10 * u.m, 4 * u.m, 6 * u.m], TypeError))
for i in checks:
with self.subTest(i=i):
self.assertRaises(i[1], pc.radius_hydraulic_rect, *i[0])
def test_radius_hydraulic_general(self):
self.assertWarns(UserWarning, pc.radius_hydraulic_general, *(6 * u.m**2, 12 * u.m))
def test_radius_hydraulic_channel(self):
"""radius_hydraulic_channel should return known results with known input."""
checks = (([6 * u.m**2, 12 * u.m], 0.5 * u.m),
([70 * u.m**2, 0.4 * u.m], 175 * u.m),
([40000 * u.m**2, 7 * u.m], 5714.285714285715 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.radius_hydraulic_channel(*i[0]), i[1])
def test_radius_hydraulic_channel_range(self):
"""radius_hydraulic_channel should not accept inputs of 0 or less."""
checks = ([0 * u.m**2, 6 * u.m], [6 * u.m**2, 0 * u.m])
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.radius_hydraulic_channel, *i)
|
class RadiusFuncsTest(QuantityTest):
'''Test the various radius-acquisition functions.'''
def test_radius_hydraulic(self):
pass
def test_radius_hydraulic_rect(self):
'''radius_hydraulic_rect should return known results with known input.'''
pass
def test_radius_hydraulic_range(self):
'''radius_hydraulic should raise errors when inputs are out of bounds.'''
pass
def test_radius_hydraulic_general(self):
pass
def test_radius_hydraulic_channel(self):
'''radius_hydraulic_channel should return known results with known input.'''
pass
def test_radius_hydraulic_channel_range(self):
'''radius_hydraulic_channel should not accept inputs of 0 or less.'''
pass
| 7 | 5 | 6 | 0 | 5 | 1 | 2 | 0.15 | 1 | 3 | 0 | 0 | 6 | 0 | 6 | 79 | 44 | 6 | 33 | 15 | 26 | 5 | 25 | 15 | 18 | 2 | 3 | 2 | 10 |
3,282 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_physchem.py
|
test_physchem.ReynoldsNumsTest
|
class ReynoldsNumsTest(QuantityTest):
"""Test the various Reynolds Number functions."""
def test_re_pipe(self):
"""re_pipe should return known results with known input."""
checks = (((12 * u.m**3/u.s, 6 * u.m, 0.01 * u.m**2/u.s), 254.64790894703253),
((12000 * u.L/u.s, 600 * u.cm, 0.000001 * u.ha/u.s), 254.64790894703253),
((60 * u.m**3/u.s, 1 * u.m, 1 * u.m**2/u.s), 76.39437268410977),
((1 * u.m**3/u.s, 12 * u.m, .45 * u.m**2/u.s), 0.23578510087688198))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.re_pipe(*i[0]), i[1]*u.dimensionless)
def test_re_pipe_range(self):
"""re_pipe should raise errors when inputs are out of bounds."""
checks = ((0 * u.m**3/u.s, 4 * u.m, .5 * u.m**2/u.s),
(1 * u.m**3/u.s, 0 * u.m, .4 * u.m**2/u.s),
(1 * u.m**3/u.s, 1 * u.m, -0.1 * u.m**2/u.s),
(1 * u.m**3/u.s, 1 * u.m, 0 * u.m**2/u.s))
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.re_pipe, *i)
def test_re_rect(self):
"""re_rect should return known result with known input."""
checks = (((10 * u.m**3/u.s, 4 * u.m, 6 * u.m, 1 * u.m**2/u.s, True), 2.5),
((8 * u.m**3/u.s, 10 * u.m, 4 * u.m, 0.6 * u.m**2/u.s, False), 1.9047619047619049),
((10000 * u.L/u.s, 4 * u.m, 6 * u.m, 0.0001 * u.ha/u.s, True), 2.5))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.re_rect(*i[0]), i[1]*u.dimensionless)
def test_re_rect_range(self):
"""re_rect should raise errors when inputs are out of bounds."""
checks = ((0 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, False),
(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 0 * u.m**2/u.s, False))
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.re_rect, *i)
def test_re_rect_warning(self):
"""re_rect should raise warnings when passed a deprecated parameter"""
checks = (lambda: pc.re_rect(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s),
lambda: pc.re_rect(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, OpenChannel=False, openchannel=False))
for i in checks:
with self.subTest(i=i):
self.assertRaises(TypeError, i)
self.assertWarns(UserWarning, lambda: pc.re_rect(1 * u.m**3/u.s, 1 * u.m, 1 * u.m, 1 * u.m**2/u.s, openchannel=False))
def test_re_general(self):
self.assertWarns(UserWarning, pc.re_general, *(1 * u.m/u.s, 2 * u.m**2, 3 * u.m, 0.4 * u.m**2/u.s))
def test_re_channel(self):
"""re_channel should return known values with known input."""
checks = (([1 * u.m/u.s, 2 * u.m**2, 3 * u.m, 0.4 * u.m**2/u.s], 6.666666666666666),
([17 * u.m/u.s, 6 * u.m**2, 42 * u.m, 1 * u.m**2/u.s], 9.714285714285714),
([0 * u.m/u.s, 1 * u.m**2, 2 * u.m, 0.3 * u.m**2/u.s], 0))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.re_channel(*i[0]), i[1]*u.dimensionless)
def test_re_channel_range(self):
"""re_channel should raise errors when inputs are out of bounds."""
checks = ((-1 * u.m/u.s, 2 * u.m**2, 3 * u.m, 0.4 * u.m**2/u.s),
(1 * u.m/u.s, 2 * u.m**2, 3 * u.m, 0 * u.m**2/u.s))
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.re_channel, *i)
|
class ReynoldsNumsTest(QuantityTest):
'''Test the various Reynolds Number functions.'''
def test_re_pipe(self):
'''re_pipe should return known results with known input.'''
pass
def test_re_pipe_range(self):
'''re_pipe should raise errors when inputs are out of bounds.'''
pass
def test_re_rect(self):
'''re_rect should return known result with known input.'''
pass
def test_re_rect_range(self):
'''re_rect should raise errors when inputs are out of bounds.'''
pass
def test_re_rect_warning(self):
'''re_rect should raise warnings when passed a deprecated parameter'''
pass
def test_re_general(self):
pass
def test_re_channel(self):
'''re_channel should return known values with known input.'''
pass
def test_re_channel_range(self):
'''re_channel should raise errors when inputs are out of bounds.'''
pass
| 9 | 8 | 7 | 0 | 6 | 1 | 2 | 0.15 | 1 | 3 | 0 | 0 | 8 | 0 | 8 | 81 | 69 | 9 | 52 | 23 | 43 | 8 | 39 | 23 | 30 | 2 | 3 | 2 | 15 |
3,283 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_physchem.py
|
test_physchem.WaterPropertiesTest
|
class WaterPropertiesTest(QuantityTest):
"""Test the density and dynamic/kinematic viscosity functions."""
def test_water_table(self):
"""The table density_water relies upon shouldn't need to be changed."""
table = pc.WATER_DENSITY_TABLE
checks = ((0, 273.15, 999.9),
(4, 303.15, 995.7),
(11, 373.15, 958.4))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqual(table[0][i[0]], i[1])
self.assertAlmostEqual(table[1][i[0]], i[2])
def test_water_table_units(self):
"""The water density table should handle units properly."""
table = pc.WATER_DENSITY_TABLE
self.assertAlmostEqual(table[0][0], (0 * u.degC).to_base_units().magnitude)
self.assertAlmostEqual(table[0][4], (30 * u.degC).to_base_units().magnitude)
def test_density_water_true(self):
"""density_water should give known result with known input."""
checks = ((273.15 * u.degK, 999.9 * u.kg/u.m**3),
(300 * u.degK, 996.601907542082 * u.kg/u.m**3),
(343.15 * u.degK, 977.8 * u.kg/u.m**3))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.density_water(i[0]), i[1])
def test_density_water_warning(self):
checks = (lambda: pc.density_water(Temperature=1 * u.degK, temp=1 * u.degK),
lambda: pc.density_water())
for i in checks:
with self.subTest(i=i):
self.assertRaises(TypeError, i)
self.assertWarns(UserWarning, lambda: pc.density_water(temp=1 * u.degK))
def test_viscosity_dynamic(self):
self.assertWarns(UserWarning, pc.viscosity_dynamic, 300 * u.degK)
def test_viscosity_dynamic_water(self):
"""viscosity_dynamic_water should give known result with known input."""
checks = ((300 * u.degK, 0.0008540578046518858 * u.kg/(u.m*u.s)),
(372 * u.degK, 0.00028238440851243975 * u.kg/(u.m*u.s)),
(274 * u.degK, 0.0017060470223965783 * u.kg/(u.m*u.s)),
(26.85 * u.degC, 0.0008540578046518858 * u.kg/(u.m*u.s)))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.viscosity_dynamic_water(i[0]), i[1])
def test_viscosity_kinematic(self):
self.assertWarns(UserWarning, pc.viscosity_kinematic, 300 * u.degK)
def test_viscosity_kinematic_water(self):
"""viscosity_kinematic_water should give known results with known input."""
checks = ((342 * u.degK, 4.1584506710898959e-07 * u.m**2/u.s),
(297 * u.degK, 9.1670473903811879e-07 * u.m**2/u.s),
(273.15 * u.degK, 1.7532330683680798e-06 * u.m**2/u.s),
(373.15 * u.degK, 2.9108883329847625e-07 * u.m**2/u.s),
(100 * u.degC, 2.9108883329847625e-07 * u.m**2/u.s))
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqualQuantity(pc.viscosity_kinematic_water(i[0]), i[1])
self.assertAlmostEqualQuantity(pc.viscosity_kinematic_water(i[0]),
(pc.viscosity_dynamic_water(i[0]) / pc.density_water(i[0])))
|
class WaterPropertiesTest(QuantityTest):
'''Test the density and dynamic/kinematic viscosity functions.'''
def test_water_table(self):
'''The table density_water relies upon shouldn't need to be changed.'''
pass
def test_water_table_units(self):
'''The water density table should handle units properly.'''
pass
def test_density_water_true(self):
'''density_water should give known result with known input.'''
pass
def test_density_water_warning(self):
pass
def test_viscosity_dynamic(self):
pass
def test_viscosity_dynamic_water(self):
'''viscosity_dynamic_water should give known result with known input.'''
pass
def test_viscosity_kinematic(self):
pass
def test_viscosity_kinematic_water(self):
'''viscosity_kinematic_water should give known results with known input.'''
pass
| 9 | 6 | 7 | 0 | 6 | 1 | 2 | 0.12 | 1 | 2 | 0 | 0 | 8 | 0 | 8 | 81 | 66 | 9 | 51 | 21 | 42 | 6 | 38 | 21 | 29 | 2 | 3 | 2 | 13 |
3,284 |
AguaClara/aguaclara
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AguaClara_aguaclara/tests/core/test_utility.py
|
test_utility.UtilityTest
|
class UtilityTest(QuantityTest):
def test_round_sig_figs(self):
self.assertAlmostEqual(ut.round_sig_figs(123456.789, 8), 123456.79)
self.assertAlmostEqual(ut.round_sig_figs(
20.01 * u.L/u.s, 2), 20 * u.L/u.s)
self.assertAlmostEqual(
ut.round_sig_figs(-456.789 * u.L/u.s, 4), -456.8 * u.L/u.s)
self.assertAlmostEqual(ut.round_sig_figs(0, 4), 0)
self.assertAlmostEqual(ut.round_sig_figs(0 * u.m, 4), 0 * u.m)
def test_floor_nearest(self):
self.assertEqual(ut.floor_nearest(1, np.array([1, 1.5, 2])), 1)
self.assertEqual(ut.floor_nearest(1, np.array([0, 1, 1.5, 2])), 1)
self.assertEqual(ut.floor_nearest(1, np.array([0.5, 1.5, 2])), 0.5)
self.assertEqual(ut.floor_nearest(1, np.array([0, 2, 1.5, 0.5])), 0.5)
self.assertEqual(ut.floor_nearest(
1, np.array([0.4, 0.2, 0.1, 0.5])), 0.5)
def test_floor_nearest_raises(self):
self.assertRaises(ValueError, ut.floor_nearest, x=1,
array=np.array([1.5, 2, 2.5]))
def test_ceil_nearest(self):
self.assertEqual(ut.ceil_nearest(2, np.array([1, 1.5, 2])), 2)
self.assertEqual(ut.ceil_nearest(1.5, np.array([1, 1.5, 2])), 1.5)
self.assertEqual(ut.ceil_nearest(1.6, np.array([0.5, 1.5, 2])), 2)
self.assertEqual(ut.ceil_nearest(1.4, np.array([0, 2, 1.5, 0.5])), 1.5)
self.assertEqual(ut.ceil_nearest(0.4, np.array([0.8, 2, 1, 0.5])), 0.5)
def test_ceil_nearest_raises(self):
self.assertRaises(ValueError, ut.ceil_nearest, x=3,
array=np.array([1.5, 2, 2.5]))
def test_max(self):
self.assertEqual(ut.max(2 * u.m, 4 * u.m), 4 * u.m)
self.assertEqual(ut.max(3 * u.m, 1 * u.m, 6 * u.m,
10 * u.m, 1.5 * u.m), 10 * u.m)
self.assertEqual(ut.max(2 * u.m), 2 * u.m)
def test_min(self):
self.assertEqual(ut.min(2 * u.m, 4 * u.m), 2 * u.m)
self.assertEqual(ut.min(3 * u.m, 1 * u.m, 6 * u.m,
10 * u.m, 1.5 * u.m), 1 * u.m)
self.assertEqual(ut.min(2 * u.m), 2 * u.m)
def test_list_handler_with_units(self):
@ut.list_handler()
def density_air(Pressure, MolarMass, Temperature):
"""Return the density of air at the given pressure, molar mass, and
temperature.
:param Pressure: pressure of air in the system
:type Pressure: u.pascal
:param MolarMass: molar mass of air in the system
:type MolarMass: u.gram/u.mol
:param Temperature: Temperature of air in the system
:type Temperature: u.degK
:return: density of air in the system
:rtype: u.kg/u.m**3
"""
return (Pressure * MolarMass / (u.R * Temperature)).to(u.kg/u.m**3)
answer = 1.29320768*u.kg/u.m**3
self.assertAlmostEqualQuantity(density_air(
1*u.atm, 28.97*u.g/u.mol, 273*u.K), answer)
answer = 1.29320768*u.kg/u.m**3
self.assertAlmostEqualQuantity(density_air(
MolarMass=28.97*u.g/u.mol, Temperature=273*u.K, Pressure=1*u.atm), answer)
answer = np.array(
[1.29320768, 2.58641536, 3.87962304, 12.93207681])*u.kg/u.m**3
self.assertAlmostEqualArrayQuantity(density_air(
[1, 2, 3, 10]*u.atm, 28.97*u.g/u.mol, 273*u.K), answer)
answer = np.array(
[1.29320768, 2.58641536, 3.87962304, 12.93207681])*u.kg/u.m**3
self.assertAlmostEqualArrayQuantity(density_air(
MolarMass=28.97*u.g/u.mol, Temperature=273*u.K, Pressure=[1, 2, 3, 10]*u.atm), answer)
answer = np.array([[1.29320768, 1.20526777, 1.07134913, 0.89279094],
[2.58641536, 2.41053555, 2.14269826, 1.78558189],
[3.87962304, 3.61580333, 3.21404740, 2.67837283],
[12.93207681, 12.05267773, 10.71349131, 8.92790943]])*u.kg/u.m**3
output = density_air([1, 2, 3, 10]*u.atm,
[28.97, 27, 24, 20]*u.g/u.mol, 273*u.K)
self.assertEqual(output.units, answer.units)
for i in range(len(output.magnitude)):
self.assertAlmostEqualArray(
output.magnitude[i], answer.magnitude[i])
def test_list_handler_dimensionless(self):
@ut.list_handler()
def re_pipe(FlowRate, Diam, Nu):
"""Return the Reynolds number of flow through a pipe.
:param FlowRate: flow rate through pipe
:type FlowRate: u.m**3/u.s
:param Diam: diameter of pipe
:type Diam: u.m
:param Nu: kinematic viscosity of fluid
:type Nu: u.m**2/u.s
:return: Reynolds number of flow through pipe
:rtype: u.dimensionless
"""
return ((4 * FlowRate) / (np.pi * Diam * Nu))
answer = 254.64790894703253 * u.dimensionless
self.assertAlmostEqualQuantity(
re_pipe(12 * u.m**3/u.s, 6 * u.m, 0.01 * u.m**2/u.s), answer)
answer = np.array([254.647908947, 218.26963624,
190.98593171]) * u.dimensionless
self.assertAlmostEqualArrayQuantity(
re_pipe(12 * u.m**3/u.s, [6, 7, 8] * u.m, 0.01 * u.m**2/u.s), answer)
answer = np.array([254.647908947, 218.26963624, 190.98593171])
self.assertAlmostEqualArray(re_pipe(12, [6, 7, 8], 0.01), answer)
|
class UtilityTest(QuantityTest):
def test_round_sig_figs(self):
pass
def test_floor_nearest(self):
pass
def test_floor_nearest_raises(self):
pass
def test_ceil_nearest(self):
pass
def test_ceil_nearest_raises(self):
pass
def test_max(self):
pass
def test_min(self):
pass
def test_list_handler_with_units(self):
pass
@ut.list_handler()
def density_air(Pressure, MolarMass, Temperature):
'''Return the density of air at the given pressure, molar mass, and
temperature.
:param Pressure: pressure of air in the system
:type Pressure: u.pascal
:param MolarMass: molar mass of air in the system
:type MolarMass: u.gram/u.mol
:param Temperature: Temperature of air in the system
:type Temperature: u.degK
:return: density of air in the system
:rtype: u.kg/u.m**3
'''
pass
def test_list_handler_dimensionless(self):
pass
@ut.list_handler()
def re_pipe(FlowRate, Diam, Nu):
'''Return the Reynolds number of flow through a pipe.
:param FlowRate: flow rate through pipe
:type FlowRate: u.m**3/u.s
:param Diam: diameter of pipe
:type Diam: u.m
:param Nu: kinematic viscosity of fluid
:type Nu: u.m**2/u.s
:return: Reynolds number of flow through pipe
:rtype: u.dimensionless
'''
pass
| 14 | 2 | 11 | 1 | 6 | 4 | 1 | 0.34 | 1 | 2 | 0 | 0 | 9 | 0 | 9 | 84 | 103 | 21 | 61 | 18 | 47 | 21 | 56 | 16 | 44 | 2 | 3 | 1 | 12 |
3,285 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_pipedatabase.py
|
test_pipedatabase.PipeTest
|
class PipeTest(unittest.TestCase):
def test_OD(self):
checks = [[1.0 * u.inch, 1.315 * u.inch]]
for i in checks:
with self.subTest(i=i):
self.assertAlmostEqual(pipe.OD(i[0]), i[1])
|
class PipeTest(unittest.TestCase):
def test_OD(self):
pass
| 2 | 0 | 5 | 0 | 5 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 6 | 0 | 6 | 4 | 4 | 0 | 6 | 4 | 4 | 2 | 2 | 2 | 2 |
3,286 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_pipes.py
|
test_pipes.TestPipes
|
class TestPipes(unittest.TestCase):
def test_pipes(self):
pipe = pipes.Pipe(nd=(7.0 * u.inch), sdr=35.0)
pipe_df = pd.read_csv(os.path.join(
os.path.dirname(__file__),
'../../aguaclara/core/data/pipe_database.csv'
))
self.assertAlmostEqual(pipe.od, 7.625 * u.inch)
self.assertAlmostEqual(pipe.id_sdr, 7.189285714285714 * u.inch)
self.assertAlmostEqual(pipe.id_sch(pipes.SCH.SCH40), 7.023 * u.inch)
self.assertAlmostEqual(pipes.ND_SDR_available(7.1892857 * u.inch, 35.0), 8.0 * u.inch)
self.assertAlmostEqual(pipes.ND_available(4.7 * u.inch), 6.0 * u.inch)
self.assertEqual(pipe.sch(), (8*u.inch, (pipes.SCH.SCH80.name)))
self.assertEqual(pipe.sch(NDarr=[10]*u.inch), (10*u.inch, (pipes.SCH.SCH160.name)))
self.assertWarns(UserWarning, lambda: pipe.id_sch40)
self.assertAlmostEqual(pipe.id_sch40, 7.023 * u.inch)
def test_OD_from_IDSDR(self):
#test that SDR=2 is undefined.
with self.assertRaises(ValueError): pipes.OD_SDR(1*u.inch,2)
#test other cases
self.assertAlmostEqual(pipes.OD_SDR(1*u.inch,2.5),6.625*u.inch)
self.assertAlmostEqual(pipes.OD_SDR(1*u.inch,2.25),10.75*u.inch)
self.assertAlmostEqual(pipes.OD_SDR(.27*u.inch,(.4/.07)),.84*u.inch)
#one that is already there
self.assertAlmostEqual(pipes.OD_SDR(4.026*u.inch,(4.5/0.237)),4.5*u.inch)
def test_makePipe_ND_SDR(self):
#used=1 at this nominal diameter
pipe = pipes.makePipe_ND_SDR(8*u.inch,5.75)
self.assertAlmostEqual(pipe.od, 8.625 * u.inch)
self.assertAlmostEqual(pipe.id_sdr, 5.625 * u.inch)
self.assertAlmostEqual(pipe.id_sch(pipes.SCH.SCH40), 7.981 * u.inch)
self.assertAlmostEqual(pipe.id_sch(pipes.SCH.SCH80), 7.625 * u.inch)
#used=0 at this nominal diameter
pipe = pipes.makePipe_ND_SDR(20*u.inch,20)
self.assertAlmostEqual(pipe.od, 20 * u.inch)
self.assertAlmostEqual(pipe.id_sdr, 18 * u.inch)
self.assertAlmostEqual(pipe.id_sch(pipes.SCH.SCH40), 19.25 * u.inch)
self.assertAlmostEqual(pipe.id_sch(pipes.SCH.SCH80), 17.938 * u.inch)
self.assertEqual(pipe.sch(), (24*u.inch, (pipes.SCH.SCH160.name)))
self.assertEqual(pipe.sch(NDarr=[24]*u.inch,SCHarr=[pipes.SCH.SCH160]), (24*u.inch, (pipes.SCH.SCH160.name)))
self.assertEqual(pipe.sch(SCHarr=[pipes.SCH.SCH160, pipes.SCH.SCH40]), (24*u.inch, (pipes.SCH.SCH160.name)))
self.assertEqual(pipe.sch(NDarr=[20,24]*u.inch), (24*u.inch, (pipes.SCH.SCH160.name)))
self.assertEqual(pipe.sch(NDarr=[16]*u.inch), None)
def test_makePipe_minID_SDR(self):
#used=0, matches with sched40 ID
pipe = pipes.makePipe_ND_SDR(.824*u.inch,1.05/.113)
self.assertAlmostEqual(pipe.od, 1.05 * u.inch)
self.assertAlmostEqual(pipe.id_sdr, .824 * u.inch)
self.assertAlmostEqual(pipe.id_sch(pipes.SCH.SCH40), .824 * u.inch)
self.assertAlmostEqual(pipe.id_sch(pipes.SCH.SCH80), .742 * u.inch)
#used=0, does not match with sched40 ID
pipe2 = pipes.makePipe_minID_SDR(.8*u.inch,5)
self.assertAlmostEqual(pipe2.od, 1.9 * u.inch)
self.assertAlmostEqual(pipe2.id_sdr, 1.14 * u.inch)
self.assertAlmostEqual(pipe2.id_sch(pipes.SCH.SCH40), 1.61 * u.inch)
self.assertAlmostEqual(pipe2.id_sch(pipes.SCH.SCH80), 1.5 * u.inch)
self.assertEqual(pipe2.sch(), None)
def test_ND_all_available(self):
ndarrsol = [0.5,1,1.5,2,3,4,6,8,10,12,16,18,24,30,36,48,60,72] * u.inch
ndarr = pipes.ND_all_available()
np.testing.assert_array_equal(ndarr.magnitude, ndarrsol.magnitude)
def test_OD_all_available(self):
odarrsol = [0.84,1.315,1.9,2.375,3.5,4.5,6.625,8.625,10.75,12.75,16,18,24,30,36,48,60,72] * u.inch
odarr = pipes.OD_all_available()
np.testing.assert_array_equal(odarr.magnitude, odarrsol.magnitude)
def test_OD(self):
#values on table
self.assertAlmostEqual(pipes.OD(.125 * u.inch), .404 * u.inch)
self.assertAlmostEqual(pipes.OD(2 * u.inch), 2.375 * u.inch)
self.assertAlmostEqual(pipes.OD(8 * u.inch), 8.625 * u.inch)
self.assertAlmostEqual(pipes.OD(46 * u.inch), 46 * u.inch)
self.assertAlmostEqual(pipes.OD(92 * u.inch), 92 * u.inch)
#values in between official NDs
self.assertAlmostEqual(pipes.OD(2.25 * u.inch), 2.375 * u.inch)
self.assertAlmostEqual(pipes.OD(4.1 * u.inch), 4.5 * u.inch)
self.assertAlmostEqual(pipes.OD(4.4 * u.inch), 5 * u.inch)
self.assertAlmostEqual(pipes.OD(4.6 * u.inch), 5 * u.inch)
self.assertAlmostEqual(pipes.OD(33 * u.inch), 32 * u.inch)
def test_sch_all_available(self):
ans = [(10*u.inch, pipes.SCH.SCH160.name),(12*u.inch, pipes.SCH.SCH160.name)]
arr = pipes.SCH_all_available(7.189285714*u.inch,10)
for i in range(len(ans)):
self.assertEqual(arr[i], ans[i])
def test_OD_SDR(self):
self.assertAlmostEqual(pipes.OD_SDR(5*u.inch, 20), 6.625*u.inch)
self.assertAlmostEqual(pipes.OD_SDR(10*u.inch, 40), 10.75*u.inch)
self.assertAlmostEqual(pipes.OD_SDR(2.5*u.inch, 10), 3.5*u.inch)
def test_ID_SCH(self):
self.assertAlmostEqual(pipes.ID_sch(20*u.inch, pipes.SCH.SCH40), 19.25 * u.inch)
self.assertAlmostEqual(pipes.ID_sch(20*u.inch, pipes.SCH.SCH80), 17.938 * u.inch)
|
class TestPipes(unittest.TestCase):
def test_pipes(self):
pass
def test_OD_from_IDSDR(self):
pass
def test_makePipe_ND_SDR(self):
pass
def test_makePipe_minID_SDR(self):
pass
def test_ND_all_available(self):
pass
def test_OD_all_available(self):
pass
def test_OD_from_IDSDR(self):
pass
def test_sch_all_available(self):
pass
def test_OD_SDR(self):
pass
def test_ID_SCH(self):
pass
| 11 | 0 | 10 | 1 | 8 | 1 | 1 | 0.11 | 1 | 5 | 2 | 0 | 10 | 0 | 10 | 82 | 110 | 20 | 81 | 23 | 70 | 9 | 79 | 23 | 68 | 2 | 2 | 1 | 11 |
3,287 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_utility.py
|
test_utility.QuantityTest
|
class QuantityTest(unittest.TestCase):
def assertAlmostEqualQuantity(self, first, second, places=7):
self.assertAlmostEqual(first.magnitude, second.magnitude, places)
self.assertEqual(first.units, second.units, places)
def assertAlmostEqualArray(self, first, second, places=7):
self.assertEqual(type(first), type(second))
for i in range(len(first)):
self.assertAlmostEqual(first[i], second[i], places)
def assertAlmostEqualArrayQuantity(self, first, second, places=7):
self.assertEqual(first.units, second.units, places)
self.assertAlmostEqualArray(first.magnitude, second.magnitude)
|
class QuantityTest(unittest.TestCase):
def assertAlmostEqualQuantity(self, first, second, places=7):
pass
def assertAlmostEqualArray(self, first, second, places=7):
pass
def assertAlmostEqualArrayQuantity(self, first, second, places=7):
pass
| 4 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 2 | 0 | 1 | 3 | 0 | 3 | 75 | 13 | 2 | 11 | 5 | 7 | 0 | 11 | 5 | 7 | 2 | 2 | 1 | 4 |
3,288 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/research/test_EPA.py
|
tests.research.test_EPA.TestEPA
|
class TestEPA(unittest.TestCase):
'''''
Test research's Environmental_Processes_Analysis
'''''
def assertAlmostEqualSequence(self, a, b, places=7):
for elt_a, elt_b in zip(a, b):
self.assertAlmostEqual(elt_a, elt_b, places)
def test_Hplus_concentration_from_pH(self):
'''''
Test function that converts pH to molarity of H+
'''''
output = epa.invpH(8.25)
self.assertEqual(output, 5.623413251903491e-09*u.mol/u.L)
output = epa.invpH(10)
self.assertEqual(output, 1e-10*u.mol/u.L)
def test_E_Advective_Dispersion(self):
output = epa.E_Advective_Dispersion(0.5, 5)
self.assertAlmostEqual(output, 0.4774864115)
output = epa.E_Advective_Dispersion(0, 5)
self.assertAlmostEqual(output, 0)
output = epa.E_Advective_Dispersion(np.array([0, 0.5, 1, 1.5, 2]), 5)
answer = np.array([0, 0.477486411, 0.630783130, 0.418173418, 0.238743205])
self.assertAlmostEqualSequence(output, answer)
|
class TestEPA(unittest.TestCase):
'''''
Test research's Environmental_Processes_Analysis
'''
def assertAlmostEqualSequence(self, a, b, places=7):
pass
def test_Hplus_concentration_from_pH(self):
'''''
Test function that converts pH to molarity of H+
'''
pass
def test_E_Advective_Dispersion(self):
pass
| 4 | 2 | 7 | 1 | 6 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 3 | 0 | 3 | 75 | 28 | 5 | 23 | 8 | 19 | 0 | 19 | 8 | 15 | 2 | 2 | 1 | 4 |
3,289 |
AguaClara/aguaclara
|
AguaClara_aguaclara/tests/core/test_physchem.py
|
test_physchem.WeirFuncsTest
|
class WeirFuncsTest(QuantityTest):
"""Test the weir functions."""
def test_width_rect_weir(self):
self.assertWarns(UserWarning, pc.width_rect_weir, *(0.005 * u.m**3/u.s, 0.2 * u.m))
def test_width_weir_rect(self):
"""width_weir_rect should return known value for known inputs."""
self.assertAlmostEqualQuantity(pc.width_weir_rect(0.005 * u.m**3/u.s, 0.2 * u.m),
0.03005386871 * u.m)
def test_width_weir_rect_range(self):
"""width_weir_rect should raise errors when inputs are out of bounds."""
checks = ((0 * u.m**3/u.s, 1 * u.m), (1 * u.m**3/u.s, 0 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.width_weir_rect, *i)
def test_headloss_weir(self):
self.assertWarns(UserWarning, pc.headloss_weir, *(0.005 * u.m**3/u.s, 1 * u.m))
def test_headloss_weir_rect(self):
"""headloss_rect_weir should return known value for known inputs."""
self.assertAlmostEqualQuantity(pc.headloss_weir_rect(0.005 * u.m**3/u.s, 1 * u.m),
0.01933289619 * u.m)
def test_headloss_weir_rect_range(self):
"""headloss_weir_rect should raise errors when inputs are out of bounds."""
checks = ((0 * u.m**3/u.s, 1 * u.m), (1 * u.m**3/u.s, 0 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.headloss_weir_rect, *i)
def test_flow_rect_weir(self):
self.assertWarns(UserWarning, pc.flow_rect_weir, *(2 * u.m, 1 * u.m))
def test_flow_weir_rect(self):
"""flow_weir_rect should return known value for known inputs."""
self.assertAlmostEqualQuantity(pc.flow_weir_rect(2 * u.m, 1 * u.m),
5.2610159627 * u.m**3/u.s)
def test_flow_weir_rect_range(self):
"""flow_weir_rect should raise errors when inputs are out of bounds."""
checks = ((0 * u.m, 1 * u.m), (1 * u.m, 0 * u.m))
for i in checks:
with self.subTest(i=i):
self.assertRaises(ValueError, pc.flow_weir_rect, *i)
|
class WeirFuncsTest(QuantityTest):
'''Test the weir functions.'''
def test_width_rect_weir(self):
pass
def test_width_weir_rect(self):
'''width_weir_rect should return known value for known inputs.'''
pass
def test_width_weir_rect_range(self):
'''width_weir_rect should raise errors when inputs are out of bounds.'''
pass
def test_headloss_weir(self):
pass
def test_headloss_weir_rect(self):
'''headloss_rect_weir should return known value for known inputs.'''
pass
def test_headloss_weir_rect_range(self):
'''headloss_weir_rect should raise errors when inputs are out of bounds.'''
pass
def test_flow_rect_weir(self):
pass
def test_flow_weir_rect(self):
'''flow_weir_rect should return known value for known inputs.'''
pass
def test_flow_weir_rect_range(self):
'''flow_weir_rect should raise errors when inputs are out of bounds.'''
pass
| 10 | 7 | 4 | 0 | 3 | 1 | 1 | 0.23 | 1 | 2 | 0 | 0 | 9 | 0 | 9 | 82 | 46 | 8 | 31 | 16 | 21 | 7 | 28 | 16 | 18 | 2 | 3 | 2 | 12 |
3,290 |
AirSage/Petrel
|
petrel/petrel/storm.py
|
petrel.storm.LogStream
|
class LogStream(object):
"""Object that implements enough of the Python stream API to be used as
sys.stdout and sys.stderr. Messages are written to the Python logger.
"""
def __init__(self, logger):
self.logger = logger
def write(self, message):
for line in message.split('\n'):
self.logger.error(line)
|
class LogStream(object):
'''Object that implements enough of the Python stream API to be used as
sys.stdout and sys.stderr. Messages are written to the Python logger.
'''
def __init__(self, logger):
pass
def write(self, message):
pass
| 3 | 1 | 3 | 0 | 3 | 0 | 2 | 0.5 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 10 | 1 | 6 | 5 | 3 | 3 | 6 | 5 | 3 | 2 | 1 | 1 | 3 |
3,291 |
AirSage/Petrel
|
petrel/petrel/storm.py
|
petrel.storm.Bolt
|
class Bolt(Task):
def __init__(self):
if TUPLE_PROFILING:
self.profiler = BoltProfiler()
else:
self.profiler = None
def initialize(self, stormconf, context):
pass
def process(self, tuple):
pass
def run(self):
global MODE
MODE = Bolt
self.shared_initialize()
profiler = self.profiler
try:
while True:
if profiler is not None: profiler.pre_read()
tup = readTuple()
if tup.is_heartbeat_tuple():
sync()
else:
if profiler is not None: profiler.post_read()
self.process(tup)
if profiler is not None: profiler.post_process()
except Exception as e:
self.report_exception('E_BOLTFAILED', e)
storm_log.exception('Caught exception in Bolt.run')
if 'tup' in locals():
# Only print the first 2000 characters of the tuple, otherwise
# the message may be too long for certain handlers (e.g.
# SysLogHandler).
storm_log.error(
'The error occurred while processing this tuple: %s',
repr(tup.values)[:2000])
|
class Bolt(Task):
def __init__(self):
pass
def initialize(self, stormconf, context):
pass
def process(self, tuple):
pass
def run(self):
pass
| 5 | 0 | 9 | 0 | 8 | 1 | 3 | 0.09 | 1 | 2 | 1 | 0 | 4 | 1 | 4 | 6 | 38 | 3 | 32 | 10 | 26 | 3 | 31 | 9 | 25 | 8 | 2 | 4 | 12 |
3,292 |
AirSage/Petrel
|
petrel/petrel/storm.py
|
petrel.storm.BasicBoltProfiler
|
class BasicBoltProfiler(object):
"""Helper class for BasicBolt. Implements some simple log-based counters for
profiling performance."""
MAX_COUNT = 1000
def __init__(self):
self.read_time = self.process_time = self.ack_time = 0.0
self.num_tuples = self.total_num_tuples = 0
self.start_interval = None
def pre_read(self):
self.t1 = time.time()
if self.start_interval is None:
self.start_interval = self.t1
def post_read(self):
self.t2 = time.time()
self.read_time += self.t2 - self.t1
def post_process(self):
self.t3 = time.time()
self.process_time += self.t3 - self.t2
def post_ack(self):
self.t4 = time.time()
self.ack_time += self.t4 - self.t3
self.num_tuples += 1
if self.num_tuples % self.MAX_COUNT == 0 or self.t4 - self.start_interval > 1.0:
self.total_num_tuples += self.num_tuples
self.total_time = self.read_time + self.process_time + self.ack_time
storm_log.debug(
'BasicBolt profile: total_num_tuples=%d, num_tuples=%d, avg_read_time=%f (%.1f%%), avg_process_time=%f (%.1f%%), avg_ack_time=%f (%.1f%%)',
self.total_num_tuples,
self.num_tuples,
self.read_time / self.num_tuples, self.read_time / self.total_time * 100.0,
self.process_time / self.num_tuples, self.process_time / self.total_time * 100.0,
self.ack_time / self.num_tuples, self.ack_time / self.total_time * 100.0)
# Clear the timing data.
self.start_interval = None
self.num_tuples = 0
self.read_time = self.process_time = self.ack_time = 0.0
|
class BasicBoltProfiler(object):
'''Helper class for BasicBolt. Implements some simple log-based counters for
profiling performance.'''
def __init__(self):
pass
def pre_read(self):
pass
def post_read(self):
pass
def post_process(self):
pass
def post_ack(self):
pass
| 6 | 1 | 7 | 0 | 6 | 0 | 1 | 0.09 | 1 | 0 | 0 | 0 | 5 | 11 | 5 | 5 | 43 | 7 | 33 | 15 | 27 | 3 | 27 | 15 | 21 | 2 | 1 | 1 | 7 |
3,293 |
AirSage/Petrel
|
petrel/petrel/storm.py
|
petrel.storm.BasicBolt
|
class BasicBolt(Task):
def __init__(self):
if TUPLE_PROFILING:
self.profiler = BasicBoltProfiler()
else:
self.profiler = None
def initialize(self, stormconf, context):
pass
def process(self, tuple):
pass
def run(self):
global MODE
MODE = Bolt
global ANCHOR_TUPLE
self.shared_initialize()
profiler = self.profiler
try:
while True:
if profiler is not None: profiler.pre_read()
tup = readTuple()
if tup.is_heartbeat_tuple():
sync()
else:
if profiler is not None: profiler.post_read()
ANCHOR_TUPLE = tup
self.process(tup)
if profiler is not None: profiler.post_process()
ack(tup)
if profiler is not None: profiler.post_ack()
except Exception as e:
storm_log.info('Caught exception')
self.report_exception('E_BOLTFAILED', e)
storm_log.exception('Caught exception in BasicBolt.run')
if 'tup' in locals():
# Only print the first 2000 characters of the tuple, otherwise
# I've seen errors because the message is too long for
# SysLogHandler.
storm_log.error(
'The error occurred while processing this tuple: %s',
repr(tup.values)[:2000])
|
class BasicBolt(Task):
def __init__(self):
pass
def initialize(self, stormconf, context):
pass
def process(self, tuple):
pass
def run(self):
pass
| 5 | 0 | 10 | 0 | 9 | 1 | 3 | 0.08 | 1 | 3 | 2 | 0 | 4 | 1 | 4 | 6 | 43 | 3 | 37 | 11 | 30 | 3 | 37 | 10 | 30 | 9 | 2 | 4 | 13 |
3,294 |
AirSage/Petrel
|
petrel/petrel/run.py
|
petrel.run.StormHandler
|
class StormHandler(logging.Handler):
def __init__(self, *l, **kw):
super(StormHandler, self).__init__(*l, **kw)
hostname = socket.gethostname().split('.')[0]
script_name = os.getenv('SCRIPT') # Should be passed by setup_*.sh.
if script_name is None:
script_name = '<unknown>'
process_id = os.getpid()
self.format_string = '[%s][%s][%d] %%s' % (hostname, script_name, process_id)
def emit(self, record):
msg = self.format(record)
for line in msg.split('\n'):
formatted_line = self.format_string % line
#print >> sys.stderr, "Calling storm.log with: %s" % formatted_line
storm.log('%s' % formatted_line)
|
class StormHandler(logging.Handler):
def __init__(self, *l, **kw):
pass
def emit(self, record):
pass
| 3 | 0 | 7 | 0 | 7 | 1 | 2 | 0.14 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 22 | 16 | 1 | 14 | 10 | 11 | 2 | 14 | 10 | 11 | 2 | 3 | 1 | 4 |
3,295 |
AirSage/Petrel
|
petrel/petrel/storm.py
|
petrel.storm.Task
|
class Task(object):
def shared_initialize(self):
conf, context = initComponent()
# These values are only available with a patched version of Storm.
self.task_index = context.get('taskIndex', -1)
self.worker_port = context.get('workerPort', -1)
self.initialize(conf, context)
def report_exception(self, base_message, exception):
parameters = (
base_message,
os.environ.get('SCRIPT', sys.argv[0]),
socket.gethostname(),
'pid', os.getpid(),
'port', self.worker_port,
'taskindex', self.task_index,
type(exception).__name__,
#str(exception),
)
#message = '%s: %s (pid %d) on %s failed with %s: %s' % parameters
message = '__'.join(str(p).replace('.', '_') for p in parameters)
sendFailureMsgToParent(message)
# Sleep for a few seconds to try and ensure Storm reads this message
# before we terminate. If it does, then our message above will appear in
# the Storm UI.
time.sleep(5)
|
class Task(object):
def shared_initialize(self):
pass
def report_exception(self, base_message, exception):
pass
| 3 | 0 | 14 | 2 | 9 | 3 | 1 | 0.32 | 1 | 2 | 0 | 3 | 2 | 2 | 2 | 2 | 29 | 4 | 19 | 8 | 16 | 6 | 11 | 8 | 8 | 1 | 1 | 0 | 2 |
3,296 |
AirSage/Petrel
|
petrel/petrel/mock.py
|
petrel.mock.MockSpout
|
class MockSpout(storm.Spout):
def __init__(self, output_fields, data):
self.output_fields = output_fields
self.data = data
self.index = 0
def declareOutputFields(self):
return self.output_fields
def nextTuple(self):
if self.index < len(self.data):
storm.emit(self.data[self.index])
self.index += 1
|
class MockSpout(storm.Spout):
def __init__(self, output_fields, data):
pass
def declareOutputFields(self):
pass
def nextTuple(self):
pass
| 4 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 3 | 3 | 10 | 13 | 2 | 11 | 7 | 7 | 0 | 11 | 7 | 7 | 2 | 3 | 1 | 4 |
3,297 |
AirSage/Petrel
|
petrel/petrel/mock.py
|
petrel.mock.Mock
|
class Mock(object):
def __init__(self):
self.output_type = {}
self.pending = defaultdict(deque)
self.processed = defaultdict(deque)
self.emitter = None
def __enter__(self):
self.old_emit = storm.emit
storm.emit = self.emit
self.old_emitMany = storm.emitMany
storm.emitMany = self.emitMany
return self
def __exit__(self, type, value, traceback):
storm.emit = self.old_emit
storm.emitMany = self.old_emitMany
def activate(self, emitter):
self.emitter = emitter
if isinstance(emitter, storm.Spout):
storm.MODE = storm.Spout
elif isinstance(emitter, (storm.Bolt, storm.BasicBolt)):
storm.MODE = storm.Bolt
else:
assert False, "Neither a spout nor a bolt!"
def emit(self, *args, **kwargs):
self.__emit(*args, **kwargs)
#return readTaskIds()
def __emit(self, *args, **kwargs):
if storm.MODE == storm.Bolt:
self.emitBolt(*args, **kwargs)
elif storm.MODE == storm.Spout:
self.emitSpout(*args, **kwargs)
def emitMany(self, *args, **kwargs):
if storm.MODE == storm.Bolt:
self.emitManyBolt(*args, **kwargs)
elif storm.MODE == storm.Spout:
self.emitManySpout(*args, **kwargs)
def emitManyBolt(self, tuples, stream=None, anchors = [], directTask=None):
for t in tuples:
self.emitBolt(t, stream, anchors, directTask)
def emitManySpout(self, tuples, stream=None, anchors = [], directTask=None):
for t in tuples:
self.emitSpout(t, stream, id, directTask)
def emitter_id(self, emitter=None):
if emitter is None:
emitter = self.emitter
return type(emitter).__name__, python_id(emitter)
def emitBolt(self, tup, stream=None, anchors = [], directTask=None):
# Nice idea, but throws off profiling
#assert len(tup) == len(self.emitter.declareOutputFields())
# TODO: We should probably be capturing "anchors" so tests can verify
# the topology is anchoring output tuples correctly.
self.pending[self.emitter_id()].append(storm.Tuple(id=None, component=None, stream=stream, task=directTask, values=tup))
def emitSpout(self, tup, stream=None, id=None, directTask=None):
# Nice idea, but throws off profiling
#assert len(tup) == len(self.emitter.declareOutputFields())
self.pending[self.emitter_id()].append(storm.Tuple(id=id, component=None, stream=stream, task=directTask, values=tup))
def read(self, source_emitter):
emitter_id = self.emitter_id(source_emitter)
result = self.pending[emitter_id].popleft()
self.processed[emitter_id].append(result)
return result
def get_output_type(self, emitter):
emitter_id = self.emitter_id(emitter)
if emitter_id not in self.output_type:
self.output_type[emitter_id] = namedtuple('%sTuple' % type(emitter).__name__, emitter.declareOutputFields())
return self.output_type[emitter_id]
@classmethod
def run_simple_topology(cls, config, emitters, result_type=NAMEDTUPLE, max_spout_emits=None):
"""Tests a simple topology. "Simple" means there it has no branches
or cycles. "emitters" is a list of emitters, starting with a spout
followed by 0 or more bolts that run in a chain."""
# The config is almost always required. The only known reason to pass
# None is when calling run_simple_topology() multiple times for the
# same components. This can be useful for testing spout ack() and fail()
# behavior.
if config is not None:
for emitter in emitters:
emitter.initialize(config, {})
with cls() as self:
# Read from the spout.
spout = emitters[0]
spout_id = self.emitter_id(spout)
old_length = -1
length = len(self.pending[spout_id])
while length > old_length and (max_spout_emits is None or length < max_spout_emits):
old_length = length
self.activate(spout)
spout.nextTuple()
length = len(self.pending[spout_id])
# For each bolt in the sequence, consume all upstream input.
for i, bolt in enumerate(emitters[1:]):
previous = emitters[i]
self.activate(bolt)
while len(self.pending[self.emitter_id(previous)]) > 0:
bolt.process(self.read(previous))
def make_storm_tuple(t, emitter):
return t
def make_python_list(t, emitter):
return list(t.values)
def make_python_tuple(t, emitter):
return tuple(t.values)
def make_named_tuple(t, emitter):
return self.get_output_type(emitter)(*t.values)
if result_type == STORM_TUPLE:
make = make_storm_tuple
elif result_type == LIST:
make = make_python_list
elif result_type == NAMEDTUPLE:
make = make_named_tuple
else:
assert False, 'Invalid result type specified: %s' % result_type
result_values = \
[ [ make(t, emitter) for t in self.processed[self.emitter_id(emitter)]] for emitter in emitters[:-1] ] + \
[ [ make(t, emitters[-1]) for t in self.pending[self.emitter_id(emitters[-1])] ] ]
return dict((k, v) for k, v in zip(emitters, result_values))
|
class Mock(object):
def __init__(self):
pass
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
pass
def activate(self, emitter):
pass
def emit(self, *args, **kwargs):
pass
def __emit(self, *args, **kwargs):
pass
def emitMany(self, *args, **kwargs):
pass
def emitManyBolt(self, tuples, stream=None, anchors = [], directTask=None):
pass
def emitManySpout(self, tuples, stream=None, anchors = [], directTask=None):
pass
def emitter_id(self, emitter=None):
pass
def emitBolt(self, tup, stream=None, anchors = [], directTask=None):
pass
def emitSpout(self, tup, stream=None, id=None, directTask=None):
pass
def read(self, source_emitter):
pass
def get_output_type(self, emitter):
pass
@classmethod
def run_simple_topology(cls, config, emitters, result_type=NAMEDTUPLE, max_spout_emits=None):
'''Tests a simple topology. "Simple" means there it has no branches
or cycles. "emitters" is a list of emitters, starting with a spout
followed by 0 or more bolts that run in a chain.'''
pass
def make_storm_tuple(t, emitter):
pass
def make_python_list(t, emitter):
pass
def make_python_tuple(t, emitter):
pass
def make_named_tuple(t, emitter):
pass
| 21 | 1 | 7 | 1 | 6 | 1 | 2 | 0.16 | 1 | 10 | 4 | 0 | 14 | 6 | 15 | 15 | 139 | 24 | 99 | 42 | 78 | 16 | 89 | 40 | 69 | 9 | 1 | 3 | 37 |
3,298 |
AirSage/Petrel
|
petrel/petrel/emitter.py
|
petrel.emitter.Spout
|
class Spout(EmitterBase, storm.Spout):
__metaclass__ = ABCMeta
|
class Spout(EmitterBase, storm.Spout):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 2 | 0 | 0 | 0 | 3 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 2 | 0 | 0 |
3,299 |
AirSage/Petrel
|
petrel/petrel/storm.py
|
petrel.storm.BoltProfiler
|
class BoltProfiler(object):
"""Helper class for Bolt. Implements some simple log-based counters for
profiling performance."""
MAX_COUNT = 1000
def __init__(self):
self.read_time = self.process_time = 0.0
self.num_tuples = self.total_num_tuples = 0
self.start_interval = None
def pre_read(self):
self.t1 = time.time()
if self.start_interval is None:
self.start_interval = self.t1
def post_read(self):
self.t2 = time.time()
self.read_time += self.t2 - self.t1
def post_process(self):
self.t3 = time.time()
self.process_time += self.t3 - self.t2
self.num_tuples += 1
if self.num_tuples % self.MAX_COUNT == 0 or self.t3 - self.start_interval > 1.0:
self.total_num_tuples += self.num_tuples
self.total_time = self.read_time + self.process_time
storm_log.debug(
'Bolt profile: total_num_tuples=%d, num_tuples=%d, avg_read_time=%f (%.1f%%), avg_process_time=%f (%.1f%%)',
self.total_num_tuples,
self.num_tuples,
self.read_time / self.num_tuples, self.read_time / self.total_time * 100.0,
self.process_time / self.num_tuples, self.process_time / self.total_time * 100.0)
# Clear the timing data.
self.start_interval = None
self.num_tuples = 0
self.read_time = self.process_time = 0.0
|
class BoltProfiler(object):
'''Helper class for Bolt. Implements some simple log-based counters for
profiling performance.'''
def __init__(self):
pass
def pre_read(self):
pass
def post_read(self):
pass
def post_process(self):
pass
| 5 | 1 | 8 | 1 | 7 | 0 | 2 | 0.1 | 1 | 0 | 0 | 0 | 4 | 9 | 4 | 4 | 38 | 6 | 29 | 13 | 24 | 3 | 24 | 13 | 19 | 2 | 1 | 1 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.