sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def update_resource_attribute(resource_attr_id, is_var, **kwargs): """ Deletes a resource attribute and all associated data. """ user_id = kwargs.get('user_id') try: ra = db.DBSession.query(ResourceAttr).filter(ResourceAttr.id == resource_attr_id).one() except NoResultFound: raise ResourceNotFoundError("Resource Attribute %s not found"%(resource_attr_id)) ra.check_write_permission(user_id) ra.is_var = is_var return 'OK'
Deletes a resource attribute and all associated data.
entailment
def delete_resource_attribute(resource_attr_id, **kwargs): """ Deletes a resource attribute and all associated data. """ user_id = kwargs.get('user_id') try: ra = db.DBSession.query(ResourceAttr).filter(ResourceAttr.id == resource_attr_id).one() except NoResultFound: raise ResourceNotFoundError("Resource Attribute %s not found"%(resource_attr_id)) ra.check_write_permission(user_id) db.DBSession.delete(ra) db.DBSession.flush() return 'OK'
Deletes a resource attribute and all associated data.
entailment
def add_resource_attribute(resource_type, resource_id, attr_id, is_var, error_on_duplicate=True, **kwargs): """ Add a resource attribute attribute to a resource. attr_is_var indicates whether the attribute is a variable or not -- this is used in simulation to indicate that this value is expected to be filled in by the simulator. """ attr = db.DBSession.query(Attr).filter(Attr.id==attr_id).first() if attr is None: raise ResourceNotFoundError("Attribute with ID %s does not exist."%attr_id) resource_i = _get_resource(resource_type, resource_id) resourceattr_qry = db.DBSession.query(ResourceAttr).filter(ResourceAttr.ref_key==resource_type) if resource_type == 'NETWORK': resourceattr_qry = resourceattr_qry.filter(ResourceAttr.network_id==resource_id) elif resource_type == 'NODE': resourceattr_qry = resourceattr_qry.filter(ResourceAttr.node_id==resource_id) elif resource_type == 'LINK': resourceattr_qry = resourceattr_qry.filter(ResourceAttr.link_id==resource_id) elif resource_type == 'GROUP': resourceattr_qry = resourceattr_qry.filter(ResourceAttr.group_id==resource_id) elif resource_type == 'PROJECT': resourceattr_qry = resourceattr_qry.filter(ResourceAttr.project_id==resource_id) else: raise HydraError('Resource type "{}" not recognised.'.format(resource_type)) resource_attrs = resourceattr_qry.all() for ra in resource_attrs: if ra.attr_id == attr_id: if not error_on_duplicate: return ra raise HydraError("Duplicate attribute. %s %s already has attribute %s" %(resource_type, resource_i.get_name(), attr.name)) attr_is_var = 'Y' if is_var == 'Y' else 'N' new_ra = resource_i.add_attribute(attr_id, attr_is_var) db.DBSession.flush() return new_ra
Add a resource attribute attribute to a resource. attr_is_var indicates whether the attribute is a variable or not -- this is used in simulation to indicate that this value is expected to be filled in by the simulator.
entailment
def add_resource_attrs_from_type(type_id, resource_type, resource_id,**kwargs): """ adds all the attributes defined by a type to a node. """ type_i = _get_templatetype(type_id) resource_i = _get_resource(resource_type, resource_id) resourceattr_qry = db.DBSession.query(ResourceAttr).filter(ResourceAttr.ref_key==resource_type) if resource_type == 'NETWORK': resourceattr_qry.filter(ResourceAttr.network_id==resource_id) elif resource_type == 'NODE': resourceattr_qry.filter(ResourceAttr.node_id==resource_id) elif resource_type == 'LINK': resourceattr_qry.filter(ResourceAttr.link_id==resource_id) elif resource_type == 'GROUP': resourceattr_qry.filter(ResourceAttr.group_id==resource_id) elif resource_type == 'PROJECT': resourceattr_qry.filter(ResourceAttr.project_id==resource_id) resource_attrs = resourceattr_qry.all() attrs = {} for res_attr in resource_attrs: attrs[res_attr.attr_id] = res_attr new_resource_attrs = [] for item in type_i.typeattrs: if attrs.get(item.attr_id) is None: ra = resource_i.add_attribute(item.attr_id) new_resource_attrs.append(ra) db.DBSession.flush() return new_resource_attrs
adds all the attributes defined by a type to a node.
entailment
def get_all_resource_attributes(ref_key, network_id, template_id=None, **kwargs): """ Get all the resource attributes for a given resource type in the network. That includes all the resource attributes for a given type within the network. For example, if the ref_key is 'NODE', then it will return all the attirbutes of all nodes in the network. This function allows a front end to pre-load an entire network's resource attribute information to reduce on function calls. If type_id is specified, only return the resource attributes within the type. """ user_id = kwargs.get('user_id') resource_attr_qry = db.DBSession.query(ResourceAttr).\ outerjoin(Node, Node.id==ResourceAttr.node_id).\ outerjoin(Link, Link.id==ResourceAttr.link_id).\ outerjoin(ResourceGroup, ResourceGroup.id==ResourceAttr.group_id).filter( ResourceAttr.ref_key == ref_key, or_( and_(ResourceAttr.node_id != None, ResourceAttr.node_id == Node.id, Node.network_id==network_id), and_(ResourceAttr.link_id != None, ResourceAttr.link_id == Link.id, Link.network_id==network_id), and_(ResourceAttr.group_id != None, ResourceAttr.group_id == ResourceGroup.id, ResourceGroup.network_id==network_id) )) if template_id is not None: attr_ids = [] rs = db.DBSession.query(TypeAttr).join(TemplateType, TemplateType.id==TypeAttr.type_id).filter( TemplateType.template_id==template_id).all() for r in rs: attr_ids.append(r.attr_id) resource_attr_qry = resource_attr_qry.filter(ResourceAttr.attr_id.in_(attr_ids)) resource_attrs = resource_attr_qry.all() return resource_attrs
Get all the resource attributes for a given resource type in the network. That includes all the resource attributes for a given type within the network. For example, if the ref_key is 'NODE', then it will return all the attirbutes of all nodes in the network. This function allows a front end to pre-load an entire network's resource attribute information to reduce on function calls. If type_id is specified, only return the resource attributes within the type.
entailment
def get_resource_attributes(ref_key, ref_id, type_id=None, **kwargs): """ Get all the resource attributes for a given resource. If type_id is specified, only return the resource attributes within the type. """ user_id = kwargs.get('user_id') resource_attr_qry = db.DBSession.query(ResourceAttr).filter( ResourceAttr.ref_key == ref_key, or_( ResourceAttr.network_id==ref_id, ResourceAttr.node_id==ref_id, ResourceAttr.link_id==ref_id, ResourceAttr.group_id==ref_id )) if type_id is not None: attr_ids = [] rs = db.DBSession.query(TypeAttr).filter(TypeAttr.type_id==type_id).all() for r in rs: attr_ids.append(r.attr_id) resource_attr_qry = resource_attr_qry.filter(ResourceAttr.attr_id.in_(attr_ids)) resource_attrs = resource_attr_qry.all() return resource_attrs
Get all the resource attributes for a given resource. If type_id is specified, only return the resource attributes within the type.
entailment
def check_attr_dimension(attr_id, **kwargs): """ Check that the dimension of the resource attribute data is consistent with the definition of the attribute. If the attribute says 'volume', make sure every dataset connected with this attribute via a resource attribute also has a dimension of 'volume'. """ attr_i = _get_attr(attr_id) datasets = db.DBSession.query(Dataset).filter(Dataset.id == ResourceScenario.dataset_id, ResourceScenario.resource_attr_id == ResourceAttr.id, ResourceAttr.attr_id == attr_id).all() bad_datasets = [] for d in datasets: if attr_i.dimension_id is None and d.unit is not None or \ attr_i.dimension_id is not None and d.unit is None or \ units.get_dimension_by_unit_id(d.unit_id) != attr_i.dimension_id: # If there is an inconsistency bad_datasets.append(d.id) if len(bad_datasets) > 0: raise HydraError("Datasets %s have a different dimension_id to attribute %s"%(bad_datasets, attr_id)) return 'OK'
Check that the dimension of the resource attribute data is consistent with the definition of the attribute. If the attribute says 'volume', make sure every dataset connected with this attribute via a resource attribute also has a dimension of 'volume'.
entailment
def get_resource_attribute(resource_attr_id, **kwargs): """ Get a specific resource attribte, by ID If type_id is Gspecified, only return the resource attributes within the type. """ resource_attr_qry = db.DBSession.query(ResourceAttr).filter( ResourceAttr.id == resource_attr_id, ) resource_attr = resource_attr_qry.first() if resource_attr is None: raise ResourceNotFoundError("Resource attribute %s does not exist", resource_attr_id) return resource_attr
Get a specific resource attribte, by ID If type_id is Gspecified, only return the resource attributes within the type.
entailment
def set_attribute_mapping(resource_attr_a, resource_attr_b, **kwargs): """ Define one resource attribute from one network as being the same as that from another network. """ user_id = kwargs.get('user_id') ra_1 = get_resource_attribute(resource_attr_a) ra_2 = get_resource_attribute(resource_attr_b) mapping = ResourceAttrMap(resource_attr_id_a = resource_attr_a, resource_attr_id_b = resource_attr_b, network_a_id = ra_1.get_network().id, network_b_id = ra_2.get_network().id ) db.DBSession.add(mapping) db.DBSession.flush() return mapping
Define one resource attribute from one network as being the same as that from another network.
entailment
def delete_attribute_mapping(resource_attr_a, resource_attr_b, **kwargs): """ Define one resource attribute from one network as being the same as that from another network. """ user_id = kwargs.get('user_id') rm = aliased(ResourceAttrMap, name='rm') log.info("Trying to delete attribute map. %s -> %s", resource_attr_a, resource_attr_b) mapping = db.DBSession.query(rm).filter( rm.resource_attr_id_a == resource_attr_a, rm.resource_attr_id_b == resource_attr_b).first() if mapping is not None: log.info("Deleting attribute map. %s -> %s", resource_attr_a, resource_attr_b) db.DBSession.delete(mapping) db.DBSession.flush() return 'OK'
Define one resource attribute from one network as being the same as that from another network.
entailment
def delete_mappings_in_network(network_id, network_2_id=None, **kwargs): """ Delete all the resource attribute mappings in a network. If another network is specified, only delete the mappings between the two networks. """ qry = db.DBSession.query(ResourceAttrMap).filter(or_(ResourceAttrMap.network_a_id == network_id, ResourceAttrMap.network_b_id == network_id)) if network_2_id is not None: qry = qry.filter(or_(ResourceAttrMap.network_a_id==network_2_id, ResourceAttrMap.network_b_id==network_2_id)) mappings = qry.all() for m in mappings: db.DBSession.delete(m) db.DBSession.flush() return 'OK'
Delete all the resource attribute mappings in a network. If another network is specified, only delete the mappings between the two networks.
entailment
def get_mappings_in_network(network_id, network_2_id=None, **kwargs): """ Get all the resource attribute mappings in a network. If another network is specified, only return the mappings between the two networks. """ qry = db.DBSession.query(ResourceAttrMap).filter(or_(ResourceAttrMap.network_a_id == network_id, ResourceAttrMap.network_b_id == network_id)) if network_2_id is not None: qry = qry.filter(or_(ResourceAttrMap.network_a_id==network_2_id, ResourceAttrMap.network_b_id==network_2_id)) return qry.all()
Get all the resource attribute mappings in a network. If another network is specified, only return the mappings between the two networks.
entailment
def get_node_mappings(node_id, node_2_id=None, **kwargs): """ Get all the resource attribute mappings in a network. If another network is specified, only return the mappings between the two networks. """ qry = db.DBSession.query(ResourceAttrMap).filter( or_( and_( ResourceAttrMap.resource_attr_id_a == ResourceAttr.id, ResourceAttr.node_id == node_id), and_( ResourceAttrMap.resource_attr_id_b == ResourceAttr.id, ResourceAttr.node_id == node_id))) if node_2_id is not None: aliased_ra = aliased(ResourceAttr, name="ra2") qry = qry.filter(or_( and_( ResourceAttrMap.resource_attr_id_a == aliased_ra.id, aliased_ra.node_id == node_2_id), and_( ResourceAttrMap.resource_attr_id_b == aliased_ra.id, aliased_ra.node_id == node_2_id))) return qry.all()
Get all the resource attribute mappings in a network. If another network is specified, only return the mappings between the two networks.
entailment
def get_link_mappings(link_id, link_2_id=None, **kwargs): """ Get all the resource attribute mappings in a network. If another network is specified, only return the mappings between the two networks. """ qry = db.DBSession.query(ResourceAttrMap).filter( or_( and_( ResourceAttrMap.resource_attr_id_a == ResourceAttr.id, ResourceAttr.link_id == link_id), and_( ResourceAttrMap.resource_attr_id_b == ResourceAttr.id, ResourceAttr.link_id == link_id))) if link_2_id is not None: aliased_ra = aliased(ResourceAttr, name="ra2") qry = qry.filter(or_( and_( ResourceAttrMap.resource_attr_id_a == aliased_ra.id, aliased_ra.link_id == link_2_id), and_( ResourceAttrMap.resource_attr_id_b == aliased_ra.id, aliased_ra.link_id == link_2_id))) return qry.all()
Get all the resource attribute mappings in a network. If another network is specified, only return the mappings between the two networks.
entailment
def get_network_mappings(network_id, network_2_id=None, **kwargs): """ Get all the mappings of network resource attributes, NOT ALL THE MAPPINGS WITHIN A NETWORK. For that, ``use get_mappings_in_network``. If another network is specified, only return the mappings between the two networks. """ qry = db.DBSession.query(ResourceAttrMap).filter( or_( and_( ResourceAttrMap.resource_attr_id_a == ResourceAttr.id, ResourceAttr.network_id == network_id), and_( ResourceAttrMap.resource_attr_id_b == ResourceAttr.id, ResourceAttr.network_id == network_id))) if network_2_id is not None: aliased_ra = aliased(ResourceAttr, name="ra2") qry = qry.filter(or_( and_( ResourceAttrMap.resource_attr_id_a == aliased_ra.id, aliased_ra.network_id == network_2_id), and_( ResourceAttrMap.resource_attr_id_b == aliased_ra.id, aliased_ra.network_id == network_2_id))) return qry.all()
Get all the mappings of network resource attributes, NOT ALL THE MAPPINGS WITHIN A NETWORK. For that, ``use get_mappings_in_network``. If another network is specified, only return the mappings between the two networks.
entailment
def check_attribute_mapping_exists(resource_attr_id_source, resource_attr_id_target, **kwargs): """ Check whether an attribute mapping exists between a source and target resource attribute. returns 'Y' if a mapping exists. Returns 'N' in all other cases. """ qry = db.DBSession.query(ResourceAttrMap).filter( ResourceAttrMap.resource_attr_id_a == resource_attr_id_source, ResourceAttrMap.resource_attr_id_b == resource_attr_id_target).all() if len(qry) > 0: return 'Y' else: return 'N'
Check whether an attribute mapping exists between a source and target resource attribute. returns 'Y' if a mapping exists. Returns 'N' in all other cases.
entailment
def get_attribute_group(group_id, **kwargs): """ Get a specific attribute group """ user_id=kwargs.get('user_id') try: group_i = db.DBSession.query(AttrGroup).filter( AttrGroup.id==group_id).one() group_i.project.check_read_permission(user_id) except NoResultFound: raise HydraError("Group %s not found" % (group_id,)) return group_i
Get a specific attribute group
entailment
def add_attribute_group(attributegroup, **kwargs): """ Add a new attribute group. An attribute group is a container for attributes which need to be grouped in some logical way. For example, if the 'attr_is_var' flag isn't expressive enough to delineate different groupings. an attribute group looks like: { 'project_id' : XXX, 'name' : 'my group name' 'description : 'my group description' (optional) 'layout' : 'my group layout' (optional) 'exclusive' : 'N' (or 'Y' ) (optional, default to 'N') } """ log.info("attributegroup.project_id %s",attributegroup.project_id) # It is None while it should be valued user_id=kwargs.get('user_id') project_i = db.DBSession.query(Project).filter(Project.id==attributegroup.project_id).one() project_i.check_write_permission(user_id) try: group_i = db.DBSession.query(AttrGroup).filter( AttrGroup.name==attributegroup.name, AttrGroup.project_id==attributegroup.project_id).one() log.info("Group %s already exists in project %s", attributegroup.name, attributegroup.project_id) except NoResultFound: group_i = AttrGroup() group_i.project_id = attributegroup.project_id group_i.name = attributegroup.name group_i.description = attributegroup.description group_i.layout = attributegroup.get_layout() group_i.exclusive = attributegroup.exclusive db.DBSession.add(group_i) db.DBSession.flush() log.info("Attribute Group %s added to project %s", attributegroup.name, attributegroup.project_id) return group_i
Add a new attribute group. An attribute group is a container for attributes which need to be grouped in some logical way. For example, if the 'attr_is_var' flag isn't expressive enough to delineate different groupings. an attribute group looks like: { 'project_id' : XXX, 'name' : 'my group name' 'description : 'my group description' (optional) 'layout' : 'my group layout' (optional) 'exclusive' : 'N' (or 'Y' ) (optional, default to 'N') }
entailment
def update_attribute_group(attributegroup, **kwargs): """ Add a new attribute group. An attribute group is a container for attributes which need to be grouped in some logical way. For example, if the 'attr_is_var' flag isn't expressive enough to delineate different groupings. an attribute group looks like: { 'project_id' : XXX, 'name' : 'my group name' 'description : 'my group description' (optional) 'layout' : 'my group layout' (optional) 'exclusive' : 'N' (or 'Y' ) (optional, default to 'N') } """ user_id=kwargs.get('user_id') if attributegroup.id is None: raise HydraError("cannot update attribute group. no ID specified") try: group_i = db.DBSession.query(AttrGroup).filter(AttrGroup.id==attributegroup.id).one() group_i.project.check_write_permission(user_id) group_i.name = attributegroup.name group_i.description = attributegroup.description group_i.layout = attributegroup.layout group_i.exclusive = attributegroup.exclusive db.DBSession.flush() log.info("Group %s in project %s updated", attributegroup.id, attributegroup.project_id) except NoResultFound: raise HydraError('No Attribute Group %s was found in project %s', attributegroup.id, attributegroup.project_id) return group_i
Add a new attribute group. An attribute group is a container for attributes which need to be grouped in some logical way. For example, if the 'attr_is_var' flag isn't expressive enough to delineate different groupings. an attribute group looks like: { 'project_id' : XXX, 'name' : 'my group name' 'description : 'my group description' (optional) 'layout' : 'my group layout' (optional) 'exclusive' : 'N' (or 'Y' ) (optional, default to 'N') }
entailment
def delete_attribute_group(group_id, **kwargs): """ Delete an attribute group. """ user_id = kwargs['user_id'] try: group_i = db.DBSession.query(AttrGroup).filter(AttrGroup.id==group_id).one() group_i.project.check_write_permission(user_id) db.DBSession.delete(group_i) db.DBSession.flush() log.info("Group %s in project %s deleted", group_i.id, group_i.project_id) except NoResultFound: raise HydraError('No Attribute Group %s was found', group_id) return 'OK'
Delete an attribute group.
entailment
def get_network_attributegroup_items(network_id, **kwargs): """ Get all the group items in a network """ user_id=kwargs.get('user_id') net_i = _get_network(network_id) net_i.check_read_permission(user_id) group_items_i = db.DBSession.query(AttrGroupItem).filter( AttrGroupItem.network_id==network_id).all() return group_items_i
Get all the group items in a network
entailment
def get_group_attributegroup_items(network_id, group_id, **kwargs): """ Get all the items in a specified group, within a network """ user_id=kwargs.get('user_id') network_i = _get_network(network_id) network_i.check_read_permission(user_id) group_items_i = db.DBSession.query(AttrGroupItem).filter( AttrGroupItem.network_id==network_id, AttrGroupItem.group_id==group_id).all() return group_items_i
Get all the items in a specified group, within a network
entailment
def get_attribute_item_groups(network_id, attr_id, **kwargs): """ Get all the group items in a network with a given attribute_id """ user_id=kwargs.get('user_id') network_i = _get_network(network_id) network_i.check_read_permission(user_id) group_items_i = db.DBSession.query(AttrGroupItem).filter( AttrGroupItem.network_id==network_id, AttrGroupItem.attr_id==attr_id).all() return group_items_i
Get all the group items in a network with a given attribute_id
entailment
def add_attribute_group_items(attributegroupitems, **kwargs): """ Populate attribute groups with items. ** attributegroupitems : a list of items, of the form: ```{ 'attr_id' : X, 'group_id' : Y, 'network_id' : Z, }``` Note that this approach supports the possibility of populating groups within multiple networks at the same time. When adding a group item, the function checks whether it can be added, based on the 'exclusivity' setup of the groups -- if a group is specified as being 'exclusive', then any attributes within that group cannot appear in any other group (within a network). """ user_id=kwargs.get('user_id') if not isinstance(attributegroupitems, list): raise HydraError("Cannpt add attribute group items. Attributegroupitems must be a list") new_agis_i = [] group_lookup = {} #for each network, keep track of what attributes are contained in which groups it's in #structure: {NETWORK_ID : {ATTR_ID: [GROUP_ID]} agi_lookup = {} network_lookup = {} #'agi' = shorthand for 'attribute group item' for agi in attributegroupitems: network_i = network_lookup.get(agi.network_id) if network_i is None: network_i = _get_network(agi.network_id) network_lookup[agi.network_id] = network_i network_i.check_write_permission(user_id) #Get the group so we can check for exclusivity constraints group_i = group_lookup.get(agi.group_id) if group_i is None: group_lookup[agi.group_id] = _get_attr_group(agi.group_id) network_agis = agi_lookup #Create a map of all agis currently in the network if agi_lookup.get(agi.network_id) is None: agi_lookup[agi.network_id] = {} network_agis = _get_attributegroupitems(agi.network_id) log.info(network_agis) for net_agi in network_agis: if net_agi.group_id not in group_lookup: group_lookup[net_agi.group_id] = _get_attr_group(net_agi.group_id) if agi_lookup.get(net_agi.network_id) is None: agi_lookup[net_agi.network_id][net_agi.attr_id] = [net_agi.group_id] else: if agi_lookup[net_agi.network_id].get(net_agi.attr_id) is None: agi_lookup[net_agi.network_id][net_agi.attr_id] = [net_agi.group_id] elif net_agi.group_id not in agi_lookup[net_agi.network_id][net_agi.attr_id]: agi_lookup[net_agi.network_id][net_agi.attr_id].append(net_agi.group_id) #Does this agi exist anywhere else inside this network? #Go through all the groups that this attr is in and make sure it's not exclusive if agi_lookup[agi.network_id].get(agi.attr_id) is not None: for group_id in agi_lookup[agi.network_id][agi.attr_id]: group = group_lookup[group_id] #Another group has been found. if group.exclusive == 'Y': #The other group is exclusive, so this attr can't be added raise HydraError("Attribute %s is already in Group %s for network %s. This group is exclusive, so attr %s cannot exist in another group."%(agi.attr_id, group.id, agi.network_id, agi.attr_id)) #Now check that if this group is exclusive, then the attr isn't in #any other groups if group_lookup[agi.group_id].exclusive == 'Y': if len(agi_lookup[agi.network_id][agi.attr_id]) > 0: #The other group is exclusive, so this attr can't be added raise HydraError("Cannot add attribute %s to group %s. This group is exclusive, but attr %s has been found in other groups (%s)" % (agi.attr_id, agi.group_id, agi.attr_id, agi_lookup[agi.network_id][agi.attr_id])) agi_i = AttrGroupItem() agi_i.network_id = agi.network_id agi_i.group_id = agi.group_id agi_i.attr_id = agi.attr_id #Update the lookup table in preparation for the next pass. if agi_lookup[agi.network_id].get(agi.attr_id) is None: agi_lookup[agi.network_id][agi.attr_id] = [agi.group_id] elif agi.group_id not in agi_lookup[agi.network_id][agi.attr_id]: agi_lookup[agi.network_id][agi.attr_id].append(agi.group_id) db.DBSession.add(agi_i) new_agis_i.append(agi_i) log.info(agi_lookup) db.DBSession.flush() return new_agis_i
Populate attribute groups with items. ** attributegroupitems : a list of items, of the form: ```{ 'attr_id' : X, 'group_id' : Y, 'network_id' : Z, }``` Note that this approach supports the possibility of populating groups within multiple networks at the same time. When adding a group item, the function checks whether it can be added, based on the 'exclusivity' setup of the groups -- if a group is specified as being 'exclusive', then any attributes within that group cannot appear in any other group (within a network).
entailment
def delete_attribute_group_items(attributegroupitems, **kwargs): """ remove attribute groups items . ** attributegroupitems : a list of items, of the form: ```{ 'attr_id' : X, 'group_id' : Y, 'network_id' : Z, }``` """ user_id=kwargs.get('user_id') log.info("Deleting %s attribute group items", len(attributegroupitems)) #if there area attributegroupitems from different networks, keep track of those #networks to ensure the user actually has permission to remove the items. network_lookup = {} if not isinstance(attributegroupitems, list): raise HydraError("Cannpt add attribute group items. Attributegroupitems must be a list") #'agi' = shorthand for 'attribute group item' for agi in attributegroupitems: network_i = network_lookup.get(agi.network_id) if network_i is None: network_i = _get_network(agi.network_id) network_lookup[agi.network_id] = network_i network_i.check_write_permission(user_id) agi_i = db.DBSession.query(AttrGroupItem).filter(AttrGroupItem.network_id == agi.network_id, AttrGroupItem.group_id == agi.group_id, AttrGroupItem.attr_id == agi.attr_id).first() if agi_i is not None: db.DBSession.delete(agi_i) db.DBSession.flush() log.info("Attribute group items deleted") return 'OK'
remove attribute groups items . ** attributegroupitems : a list of items, of the form: ```{ 'attr_id' : X, 'group_id' : Y, 'network_id' : Z, }```
entailment
def share_network(network_id, usernames, read_only, share,**kwargs): """ Share a network with a list of users, identified by their usernames. The read_only flag ('Y' or 'N') must be set to 'Y' to allow write access or sharing. The share flat ('Y' or 'N') must be set to 'Y' to allow the project to be shared with other users """ user_id = kwargs.get('user_id') net_i = _get_network(network_id) net_i.check_share_permission(user_id) if read_only == 'Y': write = 'N' share = 'N' else: write = 'Y' if net_i.created_by != int(user_id) and share == 'Y': raise HydraError("Cannot share the 'sharing' ability as user %s is not" " the owner of network %s"% (user_id, network_id)) for username in usernames: user_i = _get_user(username) #Set the owner ship on the network itself net_i.set_owner(user_i.id, write=write, share=share) for o in net_i.project.owners: if o.user_id == user_i.id: break else: #Give the user read access to the containing project net_i.project.set_owner(user_i.id, write='N', share='N') db.DBSession.flush()
Share a network with a list of users, identified by their usernames. The read_only flag ('Y' or 'N') must be set to 'Y' to allow write access or sharing. The share flat ('Y' or 'N') must be set to 'Y' to allow the project to be shared with other users
entailment
def unshare_network(network_id, usernames,**kwargs): """ Un-Share a network with a list of users, identified by their usernames. """ user_id = kwargs.get('user_id') net_i = _get_network(network_id) net_i.check_share_permission(user_id) for username in usernames: user_i = _get_user(username) #Set the owner ship on the network itself net_i.unset_owner(user_i.id, write=write, share=share) db.DBSession.flush()
Un-Share a network with a list of users, identified by their usernames.
entailment
def share_project(project_id, usernames, read_only, share,**kwargs): """ Share an entire project with a list of users, identifed by their usernames. The read_only flag ('Y' or 'N') must be set to 'Y' to allow write access or sharing. The share flat ('Y' or 'N') must be set to 'Y' to allow the project to be shared with other users """ user_id = kwargs.get('user_id') proj_i = _get_project(project_id) #Is the sharing user allowed to share this project? proj_i.check_share_permission(int(user_id)) user_id = int(user_id) for owner in proj_i.owners: if user_id == owner.user_id: break else: raise HydraError("Permission Denied. Cannot share project.") if read_only == 'Y': write = 'N' share = 'N' else: write = 'Y' if proj_i.created_by != user_id and share == 'Y': raise HydraError("Cannot share the 'sharing' ability as user %s is not" " the owner of project %s"% (user_id, project_id)) for username in usernames: user_i = _get_user(username) proj_i.set_owner(user_i.id, write=write, share=share) for net_i in proj_i.networks: net_i.set_owner(user_i.id, write=write, share=share) db.DBSession.flush()
Share an entire project with a list of users, identifed by their usernames. The read_only flag ('Y' or 'N') must be set to 'Y' to allow write access or sharing. The share flat ('Y' or 'N') must be set to 'Y' to allow the project to be shared with other users
entailment
def unshare_project(project_id, usernames,**kwargs): """ Un-share a project with a list of users, identified by their usernames. """ user_id = kwargs.get('user_id') proj_i = _get_project(project_id) proj_i.check_share_permission(user_id) for username in usernames: user_i = _get_user(username) #Set the owner ship on the network itself proj_i.unset_owner(user_i.id, write=write, share=share) db.DBSession.flush()
Un-share a project with a list of users, identified by their usernames.
entailment
def set_project_permission(project_id, usernames, read, write, share,**kwargs): """ Set permissions on a project to a list of users, identifed by their usernames. The read flag ('Y' or 'N') sets read access, the write flag sets write access. If the read flag is 'N', then there is automatically no write access or share access. """ user_id = kwargs.get('user_id') proj_i = _get_project(project_id) #Is the sharing user allowed to share this project? proj_i.check_share_permission(user_id) #You cannot edit something you cannot see. if read == 'N': write = 'N' share = 'N' for username in usernames: user_i = _get_user(username) #The creator of a project must always have read and write access #to their project if proj_i.created_by == user_i.id: raise HydraError("Cannot set permissions on project %s" " for user %s as this user is the creator." % (project_id, username)) proj_i.set_owner(user_i.id, read=read, write=write) for net_i in proj_i.networks: net_i.set_owner(user_i.id, read=read, write=write, share=share) db.DBSession.flush()
Set permissions on a project to a list of users, identifed by their usernames. The read flag ('Y' or 'N') sets read access, the write flag sets write access. If the read flag is 'N', then there is automatically no write access or share access.
entailment
def set_network_permission(network_id, usernames, read, write, share,**kwargs): """ Set permissions on a network to a list of users, identifed by their usernames. The read flag ('Y' or 'N') sets read access, the write flag sets write access. If the read flag is 'N', then there is automatically no write access or share access. """ user_id = kwargs.get('user_id') net_i = _get_network(network_id) #Check if the user is allowed to share this network. net_i.check_share_permission(user_id) #You cannot edit something you cannot see. if read == 'N': write = 'N' share = 'N' for username in usernames: user_i = _get_user(username) #The creator of a network must always have read and write access #to their project if net_i.created_by == user_i.id: raise HydraError("Cannot set permissions on network %s" " for user %s as tis user is the creator." % (network_id, username)) net_i.set_owner(user_i.id, read=read, write=write, share=share) db.DBSession.flush()
Set permissions on a network to a list of users, identifed by their usernames. The read flag ('Y' or 'N') sets read access, the write flag sets write access. If the read flag is 'N', then there is automatically no write access or share access.
entailment
def hide_dataset(dataset_id, exceptions, read, write, share,**kwargs): """ Hide a particular piece of data so it can only be seen by its owner. Only an owner can hide (and unhide) data. Data with no owner cannot be hidden. The exceptions paramater lists the usernames of those with permission to view the data read, write and share indicate whether these users can read, edit and share this data. """ user_id = kwargs.get('user_id') dataset_i = _get_dataset(dataset_id) #check that I can hide the dataset if dataset_i.created_by != int(user_id): raise HydraError('Permission denied. ' 'User %s is not the owner of dataset %s' %(user_id, dataset_i.name)) dataset_i.hidden = 'Y' if exceptions is not None: for username in exceptions: user_i = _get_user(username) dataset_i.set_owner(user_i.id, read=read, write=write, share=share) db.DBSession.flush()
Hide a particular piece of data so it can only be seen by its owner. Only an owner can hide (and unhide) data. Data with no owner cannot be hidden. The exceptions paramater lists the usernames of those with permission to view the data read, write and share indicate whether these users can read, edit and share this data.
entailment
def unhide_dataset(dataset_id,**kwargs): """ Hide a particular piece of data so it can only be seen by its owner. Only an owner can hide (and unhide) data. Data with no owner cannot be hidden. The exceptions paramater lists the usernames of those with permission to view the data read, write and share indicate whether these users can read, edit and share this data. """ user_id = kwargs.get('user_id') dataset_i = _get_dataset(dataset_id) #check that I can unhide the dataset if dataset_i.created_by != int(user_id): raise HydraError('Permission denied. ' 'User %s is not the owner of dataset %s' %(user_id, dataset_i.name)) dataset_i.hidden = 'N' db.DBSession.flush()
Hide a particular piece of data so it can only be seen by its owner. Only an owner can hide (and unhide) data. Data with no owner cannot be hidden. The exceptions paramater lists the usernames of those with permission to view the data read, write and share indicate whether these users can read, edit and share this data.
entailment
def get_all_project_owners(project_ids=None, **kwargs): """ Get the project owner entries for all the requested projects. If the project_ids argument is None, return all the owner entries for ALL projects """ projowner_qry = db.DBSession.query(ProjectOwner) if project_ids is not None: projowner_qry = projowner_qry.filter(ProjectOwner.project_id.in_(project_ids)) project_owners_i = projowner_qry.all() return [JSONObject(project_owner_i) for project_owner_i in project_owners_i]
Get the project owner entries for all the requested projects. If the project_ids argument is None, return all the owner entries for ALL projects
entailment
def get_all_network_owners(network_ids=None, **kwargs): """ Get the network owner entries for all the requested networks. If the network_ids argument is None, return all the owner entries for ALL networks """ networkowner_qry = db.DBSession.query(NetworkOwner) if network_ids is not None: networkowner_qry = networkowner_qry.filter(NetworkOwner.network_id.in_(network_ids)) network_owners_i = networkowner_qry.all() return [JSONObject(network_owner_i) for network_owner_i in network_owners_i]
Get the network owner entries for all the requested networks. If the network_ids argument is None, return all the owner entries for ALL networks
entailment
def bulk_set_project_owners(project_owners, **kwargs): """ Set the project owner of multiple projects at once. Accepts a list of JSONObjects which look like: { 'project_id': XX, 'user_id' : YY, 'view' : 'Y'/ 'N' 'edit' : 'Y'/ 'N' 'share' : 'Y'/ 'N' } """ project_ids = [po.project_id for po in project_owners] existing_projowners = db.DBSession.query(ProjectOwner).filter(ProjectOwner.project_id.in_(project_ids)).all() #Create a lookup based on the unique key for this table (project_id, user_id) po_lookup = {} for po in existing_projowners: po_lookup[(po.project_id, po.user_id)] = po for project_owner in project_owners: #check if the entry is already there if po_lookup.get((project_owner.project_id, project_owner.user_id)): continue new_po = ProjectOwner() new_po.project_id = project_owner.project_id new_po.user_id = project_owner.user_id new_po.view = project_owner.view new_po.edit = project_owner.edit new_po.share = project_owner.share db.DBSession.add(new_po) db.DBSession.flush()
Set the project owner of multiple projects at once. Accepts a list of JSONObjects which look like: { 'project_id': XX, 'user_id' : YY, 'view' : 'Y'/ 'N' 'edit' : 'Y'/ 'N' 'share' : 'Y'/ 'N' }
entailment
def bulk_set_network_owners(network_owners, **kwargs): """ Set the network owner of multiple networks at once. Accepts a list of JSONObjects which look like: { 'network_id': XX, 'user_id' : YY, 'view' : 'Y'/ 'N' 'edit' : 'Y'/ 'N' 'share' : 'Y'/ 'N' } """ network_ids = [no.network_id for no in network_owners] existing_projowners = db.DBSession.query(NetworkOwner).filter(NetworkOwner.network_id.in_(network_ids)).all() #Create a lookup based on the unique key for this table (network_id, user_id) no_lookup = {} for no in existing_projowners: no_lookup[(no.network_id, no.user_id)] = no for network_owner in network_owners: #check if the entry is already there if no_lookup.get((network_owner.network_id, network_owner.user_id)): continue new_no = NetworkOwner() new_no.network_id = network_owner.network_id new_no.user_id = network_owner.user_id new_no.view = network_owner.view new_no.edit = network_owner.edit new_no.share = network_owner.share db.DBSession.add(new_no) db.DBSession.flush()
Set the network owner of multiple networks at once. Accepts a list of JSONObjects which look like: { 'network_id': XX, 'user_id' : YY, 'view' : 'Y'/ 'N' 'edit' : 'Y'/ 'N' 'share' : 'Y'/ 'N' }
entailment
def get_dataset(dataset_id,**kwargs): """ Get a single dataset, by ID """ user_id = int(kwargs.get('user_id')) if dataset_id is None: return None try: dataset_rs = db.DBSession.query(Dataset.id, Dataset.type, Dataset.unit_id, Dataset.name, Dataset.hidden, Dataset.cr_date, Dataset.created_by, DatasetOwner.user_id, null().label('metadata'), case([(and_(Dataset.hidden=='Y', DatasetOwner.user_id is not None), None)], else_=Dataset.value).label('value')).filter( Dataset.id==dataset_id).outerjoin(DatasetOwner, and_(DatasetOwner.dataset_id==Dataset.id, DatasetOwner.user_id==user_id)).one() rs_dict = dataset_rs._asdict() #convert the value row into a string as it is returned as a binary if dataset_rs.value is not None: rs_dict['value'] = str(dataset_rs.value) if dataset_rs.hidden == 'N' or (dataset_rs.hidden == 'Y' and dataset_rs.user_id is not None): metadata = db.DBSession.query(Metadata).filter(Metadata.dataset_id==dataset_id).all() rs_dict['metadata'] = metadata else: rs_dict['metadata'] = [] except NoResultFound: raise HydraError("Dataset %s does not exist."%(dataset_id)) dataset = namedtuple('Dataset', rs_dict.keys())(**rs_dict) return dataset
Get a single dataset, by ID
entailment
def clone_dataset(dataset_id,**kwargs): """ Get a single dataset, by ID """ user_id = int(kwargs.get('user_id')) if dataset_id is None: return None dataset = db.DBSession.query(Dataset).filter( Dataset.id==dataset_id).options(joinedload_all('metadata')).first() if dataset is None: raise HydraError("Dataset %s does not exist."%(dataset_id)) if dataset is not None and dataset.created_by != user_id: owner = db.DBSession.query(DatasetOwner).filter( DatasetOwner.dataset_id==Dataset.id, DatasetOwner.user_id==user_id).first() if owner is None: raise PermissionError("User %s is not an owner of dataset %s and therefore cannot clone it."%(user_id, dataset_id)) db.DBSession.expunge(dataset) make_transient(dataset) dataset.name = dataset.name + "(Clone)" dataset.id = None dataset.cr_date = None #Try to avoid duplicate metadata entries if the entry has been cloned previously for m in dataset.metadata: if m.key in ("clone_of", "cloned_by"): del(m) cloned_meta = Metadata() cloned_meta.key = "clone_of" cloned_meta.value = str(dataset_id) dataset.metadata.append(cloned_meta) cloned_meta = Metadata() cloned_meta.key = "cloned_by" cloned_meta.value = str(user_id) dataset.metadata.append(cloned_meta) dataset.set_hash() db.DBSession.add(dataset) db.DBSession.flush() cloned_dataset = db.DBSession.query(Dataset).filter( Dataset.id==dataset.id).first() return cloned_dataset
Get a single dataset, by ID
entailment
def get_datasets(dataset_ids,**kwargs): """ Get a single dataset, by ID """ user_id = int(kwargs.get('user_id')) datasets = [] if len(dataset_ids) == 0: return [] try: dataset_rs = db.DBSession.query(Dataset.id, Dataset.type, Dataset.unit_id, Dataset.name, Dataset.hidden, Dataset.cr_date, Dataset.created_by, DatasetOwner.user_id, null().label('metadata'), case([(and_(Dataset.hidden=='Y', DatasetOwner.user_id is not None), None)], else_=Dataset.value).label('value')).filter( Dataset.id.in_(dataset_ids)).outerjoin(DatasetOwner, and_(DatasetOwner.dataset_id==Dataset.id, DatasetOwner.user_id==user_id)).all() #convert the value row into a string as it is returned as a binary for dataset_row in dataset_rs: dataset_dict = dataset_row._asdict() if dataset_row.value is not None: dataset_dict['value'] = str(dataset_row.value) if dataset_row.hidden == 'N' or (dataset_row.hidden == 'Y' and dataset_row.user_id is not None): metadata = db.DBSession.query(Metadata).filter(Metadata.dataset_id == dataset_row.id).all() dataset_dict['metadata'] = metadata else: dataset_dict['metadata'] = [] datasets.append(namedtuple('Dataset', dataset_dict.keys())(**dataset_dict)) except NoResultFound: raise ResourceNotFoundError("Datasets not found.") return datasets
Get a single dataset, by ID
entailment
def search_datasets(dataset_id=None, dataset_name=None, collection_name=None, data_type=None, unit_id=None, scenario_id=None, metadata_key=None, metadata_val=None, attr_id = None, type_id = None, unconnected = None, inc_metadata='N', inc_val = 'N', page_start = 0, page_size = 2000, **kwargs): """ Get multiple datasets, based on several filters. If all filters are set to None, all datasets in the DB (that the user is allowe to see) will be returned. """ log.info("Searching datasets: \ndatset_id: %s,\n" "datset_name: %s,\n" "collection_name: %s,\n" "data_type: %s,\n" "unit_id: %s,\n" "scenario_id: %s,\n" "metadata_key: %s,\n" "metadata_val: %s,\n" "attr_id: %s,\n" "type_id: %s,\n" "unconnected: %s,\n" "inc_metadata: %s,\n" "inc_val: %s,\n" "page_start: %s,\n" "page_size: %s" % (dataset_id, dataset_name, collection_name, data_type, unit_id, scenario_id, metadata_key, metadata_val, attr_id, type_id, unconnected, inc_metadata, inc_val, page_start, page_size)) if page_size is None: page_size = config.get('SEARCH', 'page_size', 2000) user_id = int(kwargs.get('user_id')) dataset_qry = db.DBSession.query(Dataset.id, Dataset.type, Dataset.unit_id, Dataset.name, Dataset.hidden, Dataset.cr_date, Dataset.created_by, DatasetOwner.user_id, null().label('metadata'), Dataset.value ) #Dataset ID is unique, so there's no point using the other filters. #Only use other filters if the datset ID is not specified. if dataset_id is not None: dataset_qry = dataset_qry.filter( Dataset.id==dataset_id) else: if dataset_name is not None: dataset_qry = dataset_qry.filter( func.lower(Dataset.name).like("%%%s%%"%dataset_name.lower()) ) if collection_name is not None: dc = aliased(DatasetCollection) dci = aliased(DatasetCollectionItem) dataset_qry = dataset_qry.join(dc, func.lower(dc.name).like("%%%s%%"%collection_name.lower()) ).join(dci,and_( dci.collection_id == dc.id, dci.dataset_id == Dataset.id)) if data_type is not None: dataset_qry = dataset_qry.filter( func.lower(Dataset.type) == data_type.lower()) #null is a valid unit, so we need a way for the searcher #to specify that they want to search for datasets with a null unit #rather than ignoring the unit. We use 'null' to do this. if unit_id is not None: dataset_qry = dataset_qry.filter( Dataset.unit_id == unit_id) if scenario_id is not None: dataset_qry = dataset_qry.join(ResourceScenario, and_(ResourceScenario.dataset_id == Dataset.id, ResourceScenario.scenario_id == scenario_id)) if attr_id is not None: dataset_qry = dataset_qry.join( ResourceScenario, ResourceScenario.dataset_id == Dataset.id).join( ResourceAttr, and_(ResourceAttr.id==ResourceScenario.resource_attr_id, ResourceAttr.attr_id==attr_id)) if type_id is not None: dataset_qry = dataset_qry.join( ResourceScenario, ResourceScenario.dataset_id == Dataset.id).join( ResourceAttr, ResourceAttr.id==ResourceScenario.resource_attr_id).join( TypeAttr, and_(TypeAttr.attr_id==ResourceAttr.attr_id, TypeAttr.type_id==type_id)) if unconnected == 'Y': stmt = db.DBSession.query(distinct(ResourceScenario.dataset_id).label('dataset_id'), literal_column("0").label('col')).subquery() dataset_qry = dataset_qry.outerjoin( stmt, stmt.c.dataset_id == Dataset.id) dataset_qry = dataset_qry.filter(stmt.c.col == None) elif unconnected == 'N': #The dataset has to be connected to something stmt = db.DBSession.query(distinct(ResourceScenario.dataset_id).label('dataset_id'), literal_column("0").label('col')).subquery() dataset_qry = dataset_qry.join( stmt, stmt.c.dataset_id == Dataset.id) if metadata_key is not None and metadata_val is not None: dataset_qry = dataset_qry.join(Metadata, and_(Metadata.dataset_id == Dataset.id, func.lower(Metadata.key).like("%%%s%%"%metadata_key.lower()), func.lower(Metadata.value).like("%%%s%%"%metadata_val.lower()))) elif metadata_key is not None and metadata_val is None: dataset_qry = dataset_qry.join(Metadata, and_(Metadata.dataset_id == Dataset.id, func.lower(Metadata.key).like("%%%s%%"%metadata_key.lower()))) elif metadata_key is None and metadata_val is not None: dataset_qry = dataset_qry.join(Metadata, and_(Metadata.dataset_id == Dataset.id, func.lower(Metadata.value).like("%%%s%%"%metadata_val.lower()))) #All datasets must be joined on dataset owner so only datasets that the #user can see are retrieved. dataset_qry = dataset_qry.outerjoin(DatasetOwner, and_(DatasetOwner.dataset_id==Dataset.id, DatasetOwner.user_id==user_id)) dataset_qry = dataset_qry.filter(or_(Dataset.hidden=='N', and_(DatasetOwner.user_id is not None, Dataset.hidden=='Y'))) log.info(str(dataset_qry)) datasets = dataset_qry.all() log.info("Retrieved %s datasets", len(datasets)) #page the datasets: if page_start + page_size > len(datasets): page_end = None else: page_end = page_start + page_size datasets = datasets[page_start:page_end] log.info("Datasets paged from result %s to %s", page_start, page_end) datasets_to_return = [] for dataset_row in datasets: dataset_dict = dataset_row._asdict() if inc_val == 'N': dataset_dict['value'] = None else: #convert the value row into a string as it is returned as a binary if dataset_row.value is not None: dataset_dict['value'] = str(dataset_row.value) if inc_metadata=='Y': metadata = db.DBSession.query(Metadata).filter(Metadata.dataset_id==dataset_row.dataset_id).all() dataset_dict['metadata'] = metadata else: dataset_dict['metadata'] = [] dataset = namedtuple('Dataset', dataset_dict.keys())(**dataset_dict) datasets_to_return.append(dataset) return datasets_to_return
Get multiple datasets, based on several filters. If all filters are set to None, all datasets in the DB (that the user is allowe to see) will be returned.
entailment
def update_dataset(dataset_id, name, data_type, val, unit_id, metadata={}, flush=True, **kwargs): """ Update an existing dataset """ if dataset_id is None: raise HydraError("Dataset must have an ID to be updated.") user_id = kwargs.get('user_id') dataset = db.DBSession.query(Dataset).filter(Dataset.id==dataset_id).one() #This dataset been seen before, so it may be attached #to other scenarios, which may be locked. If they are locked, we must #not change their data, so new data must be created for the unlocked scenarios locked_scenarios = [] unlocked_scenarios = [] for dataset_rs in dataset.resourcescenarios: if dataset_rs.scenario.locked == 'Y': locked_scenarios.append(dataset_rs) else: unlocked_scenarios.append(dataset_rs) #Are any of these scenarios locked? if len(locked_scenarios) > 0: #If so, create a new dataset and assign to all unlocked datasets. dataset = add_dataset(data_type, val, unit_id, metadata=metadata, name=name, user_id=kwargs['user_id']) for unlocked_rs in unlocked_scenarios: unlocked_rs.dataset = dataset else: dataset.type = data_type dataset.value = val dataset.set_metadata(metadata) dataset.unit_id = unit_id dataset.name = name dataset.created_by = kwargs['user_id'] dataset.hash = dataset.set_hash() #Is there a dataset in the DB already which is identical to the updated dataset? existing_dataset = db.DBSession.query(Dataset).filter(Dataset.hash==dataset.hash, Dataset.id != dataset.id).first() if existing_dataset is not None and existing_dataset.check_user(user_id): log.warning("An identical dataset %s has been found to dataset %s." " Deleting dataset and returning dataset %s", existing_dataset.id, dataset.id, existing_dataset.id) db.DBSession.delete(dataset) dataset = existing_dataset if flush==True: db.DBSession.flush() return dataset
Update an existing dataset
entailment
def add_dataset(data_type, val, unit_id=None, metadata={}, name="", user_id=None, flush=False): """ Data can exist without scenarios. This is the mechanism whereby single pieces of data can be added without doing it through a scenario. A typical use of this would be for setting default values on types. """ d = Dataset() d.type = data_type d.value = val d.set_metadata(metadata) d.unit_id = unit_id d.name = name d.created_by = user_id d.hash = d.set_hash() try: existing_dataset = db.DBSession.query(Dataset).filter(Dataset.hash==d.hash).one() if existing_dataset.check_user(user_id): d = existing_dataset else: d.set_metadata({'created_at': datetime.datetime.now()}) d.set_hash() db.DBSession.add(d) except NoResultFound: db.DBSession.add(d) if flush == True: db.DBSession.flush() return d
Data can exist without scenarios. This is the mechanism whereby single pieces of data can be added without doing it through a scenario. A typical use of this would be for setting default values on types.
entailment
def _bulk_insert_data(bulk_data, user_id=None, source=None): """ Insert lots of datasets at once to reduce the number of DB interactions. user_id indicates the user adding the data source indicates the name of the app adding the data both user_id and source are added as metadata """ get_timing = lambda x: datetime.datetime.now() - x start_time=datetime.datetime.now() new_data = _process_incoming_data(bulk_data, user_id, source) log.info("Incoming data processed in %s", (get_timing(start_time))) existing_data = _get_existing_data(new_data.keys()) log.info("Existing data retrieved.") #The list of dataset IDS to be returned. hash_id_map = {} new_datasets = [] metadata = {} #This is what gets returned. for d in bulk_data: dataset_dict = new_data[d.hash] current_hash = d.hash #if this piece of data is already in the DB, then #there is no need to insert it! if existing_data.get(current_hash) is not None: dataset = existing_data.get(current_hash) #Is this user allowed to use this dataset? if dataset.check_user(user_id) == False: new_dataset = _make_new_dataset(dataset_dict) new_datasets.append(new_dataset) metadata[new_dataset['hash']] = dataset_dict['metadata'] else: hash_id_map[current_hash] = dataset#existing_data[current_hash] elif current_hash in hash_id_map: new_datasets.append(dataset_dict) else: #set a placeholder for a dataset_id we don't know yet. #The placeholder is the hash, which is unique to this object and #therefore easily identifiable. new_datasets.append(dataset_dict) hash_id_map[current_hash] = dataset_dict metadata[current_hash] = dataset_dict['metadata'] log.debug("Isolating new data %s", get_timing(start_time)) #Isolate only the new datasets and insert them new_data_for_insert = [] #keep track of the datasets that are to be inserted to avoid duplicate #inserts new_data_hashes = [] for d in new_datasets: if d['hash'] not in new_data_hashes: new_data_for_insert.append(d) new_data_hashes.append(d['hash']) if len(new_data_for_insert) > 0: #If we're working with mysql, we have to lock the table.. #For sqlite, this is not possible. Hence the try: except #try: # db.DBSession.execute("LOCK TABLES tDataset WRITE, tMetadata WRITE") #except OperationalError: # pass log.debug("Inserting new data %s", get_timing(start_time)) db.DBSession.bulk_insert_mappings(Dataset, new_data_for_insert) log.debug("New data Inserted %s", get_timing(start_time)) #try: # db.DBSession.execute("UNLOCK TABLES") #except OperationalError: # pass new_data = _get_existing_data(new_data_hashes) log.debug("New data retrieved %s", get_timing(start_time)) for k, v in new_data.items(): hash_id_map[k] = v _insert_metadata(metadata, hash_id_map) log.debug("Metadata inserted %s", get_timing(start_time)) returned_ids = [] for d in bulk_data: returned_ids.append(hash_id_map[d.hash]) log.info("Done bulk inserting data. %s datasets", len(returned_ids)) return returned_ids
Insert lots of datasets at once to reduce the number of DB interactions. user_id indicates the user adding the data source indicates the name of the app adding the data both user_id and source are added as metadata
entailment
def _get_metadata(dataset_ids): """ Get all the metadata for a given list of datasets """ metadata = [] if len(dataset_ids) == 0: return [] if len(dataset_ids) > qry_in_threshold: idx = 0 extent = qry_in_threshold while idx < len(dataset_ids): log.info("Querying %s metadatas", len(dataset_ids[idx:extent])) rs = db.DBSession.query(Metadata).filter(Metadata.dataset_id.in_(dataset_ids[idx:extent])).all() metadata.extend(rs) idx = idx + qry_in_threshold if idx + qry_in_threshold > len(dataset_ids): extent = len(dataset_ids) else: extent = extent +qry_in_threshold else: metadata_qry = db.DBSession.query(Metadata).filter(Metadata.dataset_id.in_(dataset_ids)) for m in metadata_qry: metadata.append(m) return metadata
Get all the metadata for a given list of datasets
entailment
def _get_datasets(dataset_ids): """ Get all the datasets in a list of dataset IDS. This must be done in chunks of 999, as sqlite can only handle 'in' with < 1000 elements. """ dataset_dict = {} datasets = [] if len(dataset_ids) > qry_in_threshold: idx = 0 extent =qry_in_threshold while idx < len(dataset_ids): log.info("Querying %s datasets", len(dataset_ids[idx:extent])) rs = db.DBSession.query(Dataset).filter(Dataset.id.in_(dataset_ids[idx:extent])).all() datasets.extend(rs) idx = idx + qry_in_threshold if idx + qry_in_threshold > len(dataset_ids): extent = len(dataset_ids) else: extent = extent + qry_in_threshold else: datasets = db.DBSession.query(Dataset).filter(Dataset.id.in_(dataset_ids)) for r in datasets: dataset_dict[r.id] = r log.info("Retrieved %s datasets", len(dataset_dict)) return dataset_dict
Get all the datasets in a list of dataset IDS. This must be done in chunks of 999, as sqlite can only handle 'in' with < 1000 elements.
entailment
def _get_collection(collection_id): """ Get a dataset collection by ID :param collection ID """ try: collection = db.DBSession.query(DatasetCollection).filter(DatasetCollection.id==collection_id).one() return collection except NoResultFound: raise ResourceNotFoundError("No dataset collection found with id %s"%collection_id)
Get a dataset collection by ID :param collection ID
entailment
def _get_collection_item(collection_id, dataset_id): """ Get a single dataset collection entry by collection ID and dataset ID :param collection ID :param dataset ID """ collection_item = db.DBSession.query(DatasetCollectionItem).\ filter(DatasetCollectionItem.collection_id==collection_id, DatasetCollectionItem.dataset_id==dataset_id).first() return collection_item
Get a single dataset collection entry by collection ID and dataset ID :param collection ID :param dataset ID
entailment
def add_dataset_to_collection(dataset_id, collection_id, **kwargs): """ Add a single dataset to a dataset collection. """ collection_i = _get_collection(collection_id) collection_item = _get_collection_item(collection_id, dataset_id) if collection_item is not None: raise HydraError("Dataset Collection %s already contains dataset %s", collection_id, dataset_id) new_item = DatasetCollectionItem() new_item.dataset_id=dataset_id new_item.collection_id=collection_id collection_i.items.append(new_item) db.DBSession.flush() return 'OK'
Add a single dataset to a dataset collection.
entailment
def remove_dataset_from_collection(dataset_id, collection_id, **kwargs): """ Add a single dataset to a dataset collection. """ collection_i = _get_collection(collection_id) collection_item = _get_collection_item(collection_id, dataset_id) if collection_item is None: raise HydraError("Dataset %s is not in collection %s.", dataset_id, collection_id) db.DBSession.delete(collection_item) db.DBSession.flush() db.DBSession.expunge_all() return 'OK'
Add a single dataset to a dataset collection.
entailment
def check_dataset_in_collection(dataset_id, collection_id, **kwargs): """ Check whether a dataset is contained inside a collection :param dataset ID :param collection ID :returns 'Y' or 'N' """ _get_collection(collection_id) collection_item = _get_collection_item(collection_id, dataset_id) if collection_item is None: return 'N' else: return 'Y'
Check whether a dataset is contained inside a collection :param dataset ID :param collection ID :returns 'Y' or 'N'
entailment
def get_collections_like_name(collection_name,**kwargs): """ Get all the datasets from the collection with the specified name """ try: collections = db.DBSession.query(DatasetCollection).filter(DatasetCollection.name.like("%%%s%%"%collection_name.lower())).all() except NoResultFound: raise ResourceNotFoundError("No dataset collection found with name %s"%collection_name) return collections
Get all the datasets from the collection with the specified name
entailment
def get_collection_datasets(collection_id,**kwargs): """ Get all the datasets from the collection with the specified name """ collection_datasets = db.DBSession.query(Dataset).filter(Dataset.id==DatasetCollectionItem.dataset_id, DatasetCollectionItem.collection_id==DatasetCollection.id, DatasetCollection.id==collection_id).all() return collection_datasets
Get all the datasets from the collection with the specified name
entailment
def get_val_at_time(dataset_id, timestamps,**kwargs): """ Given a timestamp (or list of timestamps) and some timeseries data, return the values appropriate to the requested times. If the timestamp is before the start of the timeseries data, return None If the timestamp is after the end of the timeseries data, return the last value. """ t = [] for time in timestamps: t.append(get_datetime(time)) dataset_i = db.DBSession.query(Dataset).filter(Dataset.id==dataset_id).one() #for time in t: # data.append(td.get_val(timestamp=time)) data = dataset_i.get_val(timestamp=t) if data is not None: dataset = JSONObject({'data': json.dumps(data)}) else: dataset = JSONObject({'data': None}) return dataset
Given a timestamp (or list of timestamps) and some timeseries data, return the values appropriate to the requested times. If the timestamp is before the start of the timeseries data, return None If the timestamp is after the end of the timeseries data, return the last value.
entailment
def get_multiple_vals_at_time(dataset_ids, timestamps,**kwargs): """ Given a timestamp (or list of timestamps) and a list of timeseries datasets, return the values appropriate to the requested times. If the timestamp is before the start of the timeseries data, return None If the timestamp is after the end of the timeseries data, return the last value. """ datasets = _get_datasets(dataset_ids) datetimes = [] for time in timestamps: datetimes.append(get_datetime(time)) return_vals = {} for dataset_i in datasets.values(): data = dataset_i.get_val(timestamp=datetimes) ret_data = {} if type(data) is list: for i, t in enumerate(timestamps): ret_data[t] = data[i] return_vals['dataset_%s'%dataset_i.id] = ret_data return return_vals
Given a timestamp (or list of timestamps) and a list of timeseries datasets, return the values appropriate to the requested times. If the timestamp is before the start of the timeseries data, return None If the timestamp is after the end of the timeseries data, return the last value.
entailment
def get_vals_between_times(dataset_id, start_time, end_time, timestep,increment,**kwargs): """ Retrive data between two specified times within a timeseries. The times need not be specified in the timeseries. This function will 'fill in the blanks'. Two types of data retrieval can be done. If the timeseries is timestamp-based, then start_time and end_time must be datetimes and timestep must be specified (minutes, seconds etc). 'increment' reflects the size of the timestep -- timestep = 'minutes' and increment = 2 means 'every 2 minutes'. If the timeseries is float-based (relative), then start_time and end_time must be decimal values. timestep is ignored and 'increment' represents the increment to be used between the start and end. Ex: start_time = 1, end_time = 5, increment = 1 will get times at 1, 2, 3, 4, 5 """ try: server_start_time = get_datetime(start_time) server_end_time = get_datetime(end_time) times = [server_start_time] next_time = server_start_time while next_time < server_end_time: if int(increment) == 0: raise HydraError("%s is not a valid increment for this search."%increment) next_time = next_time + datetime.timedelta(**{timestep:int(increment)}) times.append(next_time) except ValueError: try: server_start_time = Decimal(start_time) server_end_time = Decimal(end_time) times = [float(server_start_time)] next_time = server_start_time while next_time < server_end_time: next_time = float(next_time) + increment times.append(next_time) except: raise HydraError("Unable to get times. Please check to and from times.") td = db.DBSession.query(Dataset).filter(Dataset.id==dataset_id).one() log.debug("Number of times to fetch: %s", len(times)) data = td.get_val(timestamp=times) data_to_return = [] if type(data) is list: for d in data: if d is not None: data_to_return.append(list(d)) elif data is None: data_to_return = [] else: data_to_return.append(data) dataset = JSONObject({'data' : json.dumps(data_to_return)}) return dataset
Retrive data between two specified times within a timeseries. The times need not be specified in the timeseries. This function will 'fill in the blanks'. Two types of data retrieval can be done. If the timeseries is timestamp-based, then start_time and end_time must be datetimes and timestep must be specified (minutes, seconds etc). 'increment' reflects the size of the timestep -- timestep = 'minutes' and increment = 2 means 'every 2 minutes'. If the timeseries is float-based (relative), then start_time and end_time must be decimal values. timestep is ignored and 'increment' represents the increment to be used between the start and end. Ex: start_time = 1, end_time = 5, increment = 1 will get times at 1, 2, 3, 4, 5
entailment
def delete_dataset(dataset_id,**kwargs): """ Removes a piece of data from the DB. CAUTION! Use with care, as this cannot be undone easily. """ try: d = db.DBSession.query(Dataset).filter(Dataset.id==dataset_id).one() except NoResultFound: raise HydraError("Dataset %s does not exist."%dataset_id) dataset_rs = db.DBSession.query(ResourceScenario).filter(ResourceScenario.dataset_id==dataset_id).all() if len(dataset_rs) > 0: raise HydraError("Cannot delete %s. Dataset is used by one or more resource scenarios."%dataset_id) db.DBSession.delete(d) db.DBSession.flush() #Remove ORM references to children of this dataset (metadata, collection items) db.DBSession.expunge_all()
Removes a piece of data from the DB. CAUTION! Use with care, as this cannot be undone easily.
entailment
def get_notes(ref_key, ref_id, **kwargs): """ Get all the notes for a resource, identifed by ref_key and ref_ido. Returns [] if no notes are found or if the resource doesn't exist. """ notes = db.DBSession.query(Note).filter(Note.ref_key==ref_key) if ref_key == 'NETWORK': notes = notes.filter(Note.network_id == ref_id) elif ref_key == 'NODE': notes = notes.filter(Note.node_id == ref_id) elif ref_key == 'LINK': notes = notes.filter(Note.link_id == ref_id) elif ref_key == 'GROUP': notes = notes.filter(Note.group_id == ref_id) elif ref_key == 'PROJECT': notes = notes.filter(Note.project_id == ref_id) elif ref_key == 'SCENARIO': notes = notes.filter(Note.scenario_id == ref_id) else: raise HydraError("Ref Key %s not recognised.") note_rs = notes.all() return note_rs
Get all the notes for a resource, identifed by ref_key and ref_ido. Returns [] if no notes are found or if the resource doesn't exist.
entailment
def add_note(note, **kwargs): """ Add a new note """ note_i = Note() note_i.ref_key = note.ref_key note_i.set_ref(note.ref_key, note.ref_id) note_i.value = note.value note_i.created_by = kwargs.get('user_id') db.DBSession.add(note_i) db.DBSession.flush() return note_i
Add a new note
entailment
def update_note(note, **kwargs): """ Update a note """ note_i = _get_note(note.id) if note.ref_key != note_i.ref_key: raise HydraError("Cannot convert a %s note to a %s note. Please create a new note instead."%(note_i.ref_key, note.ref_key)) note_i.set_ref(note.ref_key, note.ref_id) note_i.value = note.value db.DBSession.flush() return note_i
Update a note
entailment
def purge_note(note_id, **kwargs): """ Remove a note from the DB permenantly """ note_i = _get_note(note_id) db.DBSession.delete(note_i) db.DBSession.flush()
Remove a note from the DB permenantly
entailment
def login(username, password, **kwargs): """ Login a user, returning a dict containing their user_id and session_id This does the DB login to check the credentials, and then creates a session so that requests from apps do not need to perform a login args: username (string): The user's username password(string): The user's password (unencrypted) returns: A dict containing the user_id and session_id raises: HydraError if the login fails """ user_id = util.hdb.login_user(username, password) hydra_session = session.Session({}, #This is normally a request object, but in this case is empty validate_key=config.get('COOKIES', 'VALIDATE_KEY', 'YxaDbzUUSo08b+'), type='file', cookie_expires=True, data_dir=config.get('COOKIES', 'DATA_DIR', '/tmp'), file_dir=config.get('COOKIES', 'FILE_DIR', '/tmp/auth')) hydra_session['user_id'] = user_id hydra_session['username'] = username hydra_session.save() return (user_id, hydra_session.id)
Login a user, returning a dict containing their user_id and session_id This does the DB login to check the credentials, and then creates a session so that requests from apps do not need to perform a login args: username (string): The user's username password(string): The user's password (unencrypted) returns: A dict containing the user_id and session_id raises: HydraError if the login fails
entailment
def logout(session_id, **kwargs): """ Logout a user, removing their cookie if it exists and returning 'OK' args: session_id (string): The session ID to identify the cookie to remove returns: 'OK' raises: HydraError if the logout fails """ hydra_session_object = session.SessionObject({}, #This is normally a request object, but in this case is empty validate_key=config.get('COOKIES', 'VALIDATE_KEY', 'YxaDbzUUSo08b+'), type='file', cookie_expires=True, data_dir=config.get('COOKIES', 'DATA_DIR', '/tmp'), file_dir=config.get('COOKIES', 'FILE_DIR', '/tmp/auth')) hydra_session = hydra_session_object.get_by_id(session_id) if hydra_session is not None: hydra_session.delete() hydra_session.save() return 'OK'
Logout a user, removing their cookie if it exists and returning 'OK' args: session_id (string): The session ID to identify the cookie to remove returns: 'OK' raises: HydraError if the logout fails
entailment
def get_session_user(session_id, **kwargs): """ Given a session ID, get the user ID that it is associated with args: session_id (string): The user's ID to identify the cookie to remove returns: user_id (string) or None if the session does not exist """ hydra_session_object = session.SessionObject({}, #This is normally a request object, but in this case is empty validate_key=config.get('COOKIES', 'VALIDATE_KEY', 'YxaDbzUUSo08b+'), type='file', cookie_expires=True, data_dir=config.get('COOKIES', 'DATA_DIR', '/tmp'), file_dir=config.get('COOKIES', 'FILE_DIR', '/tmp/auth')) hydra_session = hydra_session_object.get_by_id(session_id) if hydra_session is not None: return hydra_session['user_id'] return None
Given a session ID, get the user ID that it is associated with args: session_id (string): The user's ID to identify the cookie to remove returns: user_id (string) or None if the session does not exist
entailment
def array_dim(arr): """Return the size of a multidimansional array. """ dim = [] while True: try: dim.append(len(arr)) arr = arr[0] except TypeError: return dim
Return the size of a multidimansional array.
entailment
def check_array_struct(array): """ Check to ensure arrays are symmetrical, for example: [[1, 2, 3], [1, 2]] is invalid """ #If a list is transformed into a numpy array and the sub elements #of this array are still lists, then numpy failed to fully convert #the list, meaning it is not symmetrical. try: arr = np.array(array) except: raise HydraError("Array %s is not valid."%(array,)) if type(arr[0]) is list: raise HydraError("Array %s is not valid."%(array,))
Check to ensure arrays are symmetrical, for example: [[1, 2, 3], [1, 2]] is invalid
entailment
def arr_to_vector(arr): """Reshape a multidimensional array to a vector. """ dim = array_dim(arr) tmp_arr = [] for n in range(len(dim) - 1): for inner in arr: for i in inner: tmp_arr.append(i) arr = tmp_arr tmp_arr = [] return arr
Reshape a multidimensional array to a vector.
entailment
def vector_to_arr(vec, dim): """Reshape a vector to a multidimensional array with dimensions 'dim'. """ if len(dim) <= 1: return vec array = vec while len(dim) > 1: i = 0 outer_array = [] for m in range(reduce(mul, dim[0:-1])): inner_array = [] for n in range(dim[-1]): inner_array.append(array[i]) i += 1 outer_array.append(inner_array) array = outer_array dim = dim[0:-1] return array
Reshape a vector to a multidimensional array with dimensions 'dim'.
entailment
def _get_val(val, full=False): """ Get the value(s) of a dataset as a single value or as 1-d list of values. In the special case of timeseries, when a check is for time-based criteria, you can return the entire timeseries. """ try: val = val.strip() except: pass logging.debug("%s, type=%s", val, type(val)) if isinstance(val, float): return val if isinstance(val, int): return val if isinstance(val, np.ndarray): return list(val) try: val = float(val) return val except: pass try: val = int(val) return val except: pass if type(val) == pd.DataFrame: if full: return val newval = [] values = val.values for v in values: newv = _get_val(v) if type(newv) == list: newval.extend(newv) else: newval.append(newv) val = newval elif type(val) == dict: if full: return val newval = [] for v in val.values(): newv = _get_val(v) if type(newv) == list: newval.extend(newv) else: newval.append(newv) val = newval elif type(val) == list or type(val) == np.ndarray: newval = [] for arr_val in val: v = _get_val(arr_val) newval.append(v) val = newval return val
Get the value(s) of a dataset as a single value or as 1-d list of values. In the special case of timeseries, when a check is for time-based criteria, you can return the entire timeseries.
entailment
def get_restriction_as_dict(restriction_xml): """ turn: :: <restrictions> <restriction> <type>MAXLEN</type> <value>3</value> </restriction> <restriction> <type>VALUERANGE</type> <value><item>1</item><item>10</item></value> </restriction> </restrictions> into: :: { 'MAXLEN' : 3, 'VALUERANGE' : [1, 10] } """ restriction_dict = {} if restriction_xml is None: return restriction_dict if restriction_xml.find('restriction') is not None: restrictions = restriction_xml.findall('restriction') for restriction in restrictions: restriction_type = restriction.find('type').text restriction_val = restriction.find('value') val = None if restriction_val is not None: if restriction_val.text.strip() != "": val = _get_val(restriction_val.text) else: items = restriction_val.findall('item') val = [] for item in items: val.append(_get_val(item.text)) restriction_dict[restriction_type] = val return restriction_dict
turn: :: <restrictions> <restriction> <type>MAXLEN</type> <value>3</value> </restriction> <restriction> <type>VALUERANGE</type> <value><item>1</item><item>10</item></value> </restriction> </restrictions> into: :: { 'MAXLEN' : 3, 'VALUERANGE' : [1, 10] }
entailment
def validate_ENUM(in_value, restriction): """ Test to ensure that the given value is contained in the provided list. the value parameter must be either a single value or a 1-dimensional list. All the values in this list must satisfy the ENUM """ value = _get_val(in_value) if type(value) is list: for subval in value: if type(subval) is tuple: subval = subval[1] validate_ENUM(subval, restriction) else: if value not in restriction: raise ValidationError("ENUM : %s"%(restriction))
Test to ensure that the given value is contained in the provided list. the value parameter must be either a single value or a 1-dimensional list. All the values in this list must satisfy the ENUM
entailment
def validate_NUMPLACES(in_value, restriction): """ the value parameter must be either a single value or a 1-dimensional list. All the values in this list must satisfy the condition """ #Sometimes restriction values can accidentally be put in the template <item>100</items>, #Making them a list, not a number. Rather than blowing up, just get value 1 from the list. if type(restriction) is list: restriction = restriction[0] value = _get_val(in_value) if type(value) is list: for subval in value: if type(subval) is tuple: subval = subval[1] validate_NUMPLACES(subval, restriction) else: restriction = int(restriction) # Just in case.. dec_val = Decimal(str(value)) num_places = dec_val.as_tuple().exponent * -1 #exponent returns a negative num if restriction != num_places: raise ValidationError("NUMPLACES: %s"%(restriction))
the value parameter must be either a single value or a 1-dimensional list. All the values in this list must satisfy the condition
entailment
def validate_VALUERANGE(in_value, restriction): """ Test to ensure that a value sits between a lower and upper bound. Parameters: A Decimal value and a tuple, containing a lower and upper bound, both as Decimal values. """ if len(restriction) != 2: raise ValidationError("Template ERROR: Only two values can be specified in a date range.") value = _get_val(in_value) if type(value) is list: for subval in value: if type(subval) is tuple: subval = subval[1] validate_VALUERANGE(subval, restriction) else: min_val = Decimal(restriction[0]) max_val = Decimal(restriction[1]) val = Decimal(value) if val < min_val or val > max_val: raise ValidationError("VALUERANGE: %s, %s"%(min_val, max_val))
Test to ensure that a value sits between a lower and upper bound. Parameters: A Decimal value and a tuple, containing a lower and upper bound, both as Decimal values.
entailment
def validate_DATERANGE(value, restriction): """ Test to ensure that the times in a timeseries fall between a lower and upper bound Parameters: A timeseries in the form [(datetime, val), (datetime, val)..] and a tuple containing the lower and upper bound as datetime objects. """ if len(restriction) != 2: raise ValidationError("Template ERROR: Only two values can be specified in a date range.") if type(value) == pd.DataFrame: dates = [get_datetime(v) for v in list(value.index)] else: dates = value if type(dates) is list: for date in dates: validate_DATERANGE(date, restriction) return min_date = get_datetime(restriction[0]) max_date = get_datetime(restriction[1]) if value < min_date or value > max_date: raise ValidationError("DATERANGE: %s <%s> %s"%(min_date,value,max_date))
Test to ensure that the times in a timeseries fall between a lower and upper bound Parameters: A timeseries in the form [(datetime, val), (datetime, val)..] and a tuple containing the lower and upper bound as datetime objects.
entailment
def validate_MAXLEN(value, restriction): """ Test to ensure that a list has the prescribed length. Parameters: A list and an integer, which defines the required length of the list. """ #Sometimes restriction values can accidentally be put in the template <item>100</items>, #Making them a list, not a number. Rather than blowing up, just get value 1 from the list. if type(restriction) is list: restriction = restriction[0] else: return if len(value) > restriction: raise ValidationError("MAXLEN: %s"%(restriction))
Test to ensure that a list has the prescribed length. Parameters: A list and an integer, which defines the required length of the list.
entailment
def validate_LESSTHAN(in_value, restriction): """ Test to ensure that a value is less than a prescribed value. Parameter: Two values, which will be compared for the difference.. """ #Sometimes restriction values can accidentally be put in the template <item>100</items>, #Making them a list, not a number. Rather than blowing up, just get value 1 from the list. if type(restriction) is list: restriction = restriction[0] value = _get_val(in_value) if type(value) is list: for subval in value: if type(subval) is tuple: subval = subval[1] validate_LESSTHAN(subval, restriction) else: try: if value >= restriction: raise ValidationError("LESSTHAN: %s"%(restriction)) except TypeError: # Incompatible types for comparison. raise ValidationError("LESSTHAN: Incompatible types %s"%(restriction))
Test to ensure that a value is less than a prescribed value. Parameter: Two values, which will be compared for the difference..
entailment
def validate_LESSTHANEQ(value, restriction): """ Test to ensure that a value is less than or equal to a prescribed value. Parameter: Two values, which will be compared for the difference.. """ #Sometimes restriction values can accidentally be put in the template <item>100</items>, #Making them a list, not a number. Rather than blowing up, just get value 1 from the list. if type(restriction) is list: restriction = restriction[0] value = _get_val(value) if type(value) is list: for subval in value: if type(subval) is tuple: subval = subval[1] validate_LESSTHANEQ(subval, restriction) else: try: if value > restriction: raise ValidationError("LESSTHANEQ: %s" % (restriction)) except TypeError: # Incompatible types for comparison. raise ValidationError("LESSTHANEQ: Incompatible types %s"%(restriction))
Test to ensure that a value is less than or equal to a prescribed value. Parameter: Two values, which will be compared for the difference..
entailment
def validate_SUMTO(in_value, restriction): """ Test to ensure the values of a list sum to a specified value: Parameters: a list of numeric values and a target to which the values in the list must sum """ #Sometimes restriction values can accidentally be put in the template <item>100</items>, #Making them a list, not a number. Rather than blowing up, just get value 1 from the list. if type(restriction) is list: restriction = restriction[0] value = _get_val(in_value, full=True) if len(value) == 0: return flat_list = _flatten_value(value) try: sum(flat_list) except: raise ValidationError("List cannot be summed: %s"%(flat_list,)) if sum(flat_list) != restriction: raise ValidationError("SUMTO: %s"%(restriction))
Test to ensure the values of a list sum to a specified value: Parameters: a list of numeric values and a target to which the values in the list must sum
entailment
def validate_INCREASING(in_value, restriction): """ Test to ensure the values in a list are increasing. Parameters: a list of values and None. The none is there simply to conform with the rest of the validation routines. """ flat_list = _flatten_value(in_value) previous = None for a in flat_list: if previous is None: previous = a continue try: if a < previous: raise ValidationError("INCREASING") except TypeError: raise ValueError("INCREASING: Incompatible types") previous = a
Test to ensure the values in a list are increasing. Parameters: a list of values and None. The none is there simply to conform with the rest of the validation routines.
entailment
def validate_EQUALTIMESTEPS(value, restriction): """ Ensure that the timesteps in a timeseries are equal. If a restriction is provided, they must be equal to the specified restriction. Value is a pandas dataframe. """ if len(value) == 0: return if type(value) == pd.DataFrame: if str(value.index[0]).startswith('9999'): tmp_val = value.to_json().replace('9999', '1900') value = pd.read_json(tmp_val) #If the timeseries is not datetime-based, check for a consistent timestep if type(value.index) == pd.Int64Index: timesteps = list(value.index) timestep = timesteps[1] - timesteps[0] for i, t in enumerate(timesteps[1:]): if timesteps[i] - timesteps[i-1] != timestep: raise ValidationError("Timesteps not equal: %s"%(list(value.index))) if not hasattr(value.index, 'inferred_freq'): raise ValidationError("Timesteps not equal: %s"%(list(value.index),)) if restriction is None: if value.index.inferred_freq is None: raise ValidationError("Timesteps not equal: %s"%(list(value.index),)) else: if value.index.inferred_freq != restriction: raise ValidationError("Timesteps not equal: %s"%(list(value.index),))
Ensure that the timesteps in a timeseries are equal. If a restriction is provided, they must be equal to the specified restriction. Value is a pandas dataframe.
entailment
def _flatten_value(value): """ 1: Turn a multi-dimensional array into a 1-dimensional array 2: Turn a timeseries of values into a single 1-dimensional array """ if type(value) == pd.DataFrame: value = value.values.tolist() if type(value) != list: raise ValidationError("Value %s cannot be processed."%(value)) if len(value) == 0: return flat_list = _flatten_list(value) return flat_list
1: Turn a multi-dimensional array into a 1-dimensional array 2: Turn a timeseries of values into a single 1-dimensional array
entailment
def count_levels(value): """ Count how many levels are in a dict: scalar, list etc = 0 {} = 0 {'a':1} = 1 {'a' : {'b' : 1}} = 2 etc... """ if not isinstance(value, dict) or len(value) == 0: return 0 elif len(value) == 0: return 0 #An emptu dict has 0 else: nextval = list(value.values())[0] return 1 + count_levels(nextval)
Count how many levels are in a dict: scalar, list etc = 0 {} = 0 {'a':1} = 1 {'a' : {'b' : 1}} = 2 etc...
entailment
def flatten_dict(value, target_depth=1, depth=None): """ Take a hashtable with multiple nested dicts and return a dict where the keys are a concatenation of each sub-key. The depth of the returned array is dictated by target_depth, defaulting to 1 ex: {'a' : {'b':1, 'c': 2}} ==> {'a_b': 1, 'a_c': 2} Assumes a constant structure actoss all sub-dicts. i.e. there isn't one sub-dict with values that are both numbers and sub-dicts. """ #failsafe in case someone specified null if target_depth is None: target_depth = 1 values = list(value.values()) if len(values) == 0: return {} else: if depth is None: depth = count_levels(value) if isinstance(values[0], dict) and len(values[0]) > 0: subval = list(values[0].values())[0] if not isinstance(subval, dict) != 'object': return value if target_depth >= depth: return value flatval = {} for k in value.keys(): subval = flatten_dict(value[k], target_depth, depth-1) for k1 in subval.keys(): flatval[str(k)+"_"+str(k1)] = subval[k1]; return flatval else: return value
Take a hashtable with multiple nested dicts and return a dict where the keys are a concatenation of each sub-key. The depth of the returned array is dictated by target_depth, defaulting to 1 ex: {'a' : {'b':1, 'c': 2}} ==> {'a_b': 1, 'a_c': 2} Assumes a constant structure actoss all sub-dicts. i.e. there isn't one sub-dict with values that are both numbers and sub-dicts.
entailment
def to_named_tuple(keys, values): """ Convert a sqlalchemy object into a named tuple """ values = [dbobject.__dict__[key] for key in dbobject.keys()] tuple_object = namedtuple('DBObject', dbobject.keys()) tuple_instance = tuple_object._make(values) return tuple_instance
Convert a sqlalchemy object into a named tuple
entailment
def get_val(dataset, timestamp=None): """ Turn the string value of a dataset into an appropriate value, be it a decimal value, array or time series. If a timestamp is passed to this function, return the values appropriate to the requested times. If the timestamp is *before* the start of the timeseries data, return None If the timestamp is *after* the end of the timeseries data, return the last value. The raw flag indicates whether timeseries should be returned raw -- exactly as they are in the DB (a timeseries being a list of timeseries data objects, for example) or as a single python dictionary """ if dataset.type == 'array': #TODO: design a mechansim to retrieve this data if it's stored externally return json.loads(dataset.value) elif dataset.type == 'descriptor': return str(dataset.value) elif dataset.type == 'scalar': return Decimal(str(dataset.value)) elif dataset.type == 'timeseries': #TODO: design a mechansim to retrieve this data if it's stored externally val = dataset.value seasonal_year = config.get('DEFAULT','seasonal_year', '1678') seasonal_key = config.get('DEFAULT', 'seasonal_key', '9999') val = dataset.value.replace(seasonal_key, seasonal_year) timeseries = pd.read_json(val, convert_axes=True) if timestamp is None: return timeseries else: try: idx = timeseries.index #Seasonal timeseries are stored in the year #1678 (the lowest year pandas allows for valid times). #Therefore if the timeseries is seasonal, #the request must be a seasonal request, not a #standard request if type(idx) == pd.DatetimeIndex: if set(idx.year) == set([int(seasonal_year)]): if isinstance(timestamp, list): seasonal_timestamp = [] for t in timestamp: t_1900 = t.replace(year=int(seasonal_year)) seasonal_timestamp.append(t_1900) timestamp = seasonal_timestamp else: timestamp = [timestamp.replace(year=int(seasonal_year))] pandas_ts = timeseries.reindex(timestamp, method='ffill') #If there are no values at all, just return None if len(pandas_ts.dropna()) == 0: return None #Replace all numpy NAN values with None pandas_ts = pandas_ts.where(pandas_ts.notnull(), None) val_is_array = False if len(pandas_ts.columns) > 1: val_is_array = True if val_is_array: if type(timestamp) is list and len(timestamp) == 1: ret_val = pandas_ts.loc[timestamp[0]].values.tolist() else: ret_val = pandas_ts.loc[timestamp].values.tolist() else: col_name = pandas_ts.loc[timestamp].columns[0] if type(timestamp) is list and len(timestamp) == 1: ret_val = pandas_ts.loc[timestamp[0]].loc[col_name] else: ret_val = pandas_ts.loc[timestamp][col_name].values.tolist() return ret_val except Exception as e: log.critical("Unable to retrive data. Check timestamps.") log.critical(e)
Turn the string value of a dataset into an appropriate value, be it a decimal value, array or time series. If a timestamp is passed to this function, return the values appropriate to the requested times. If the timestamp is *before* the start of the timeseries data, return None If the timestamp is *after* the end of the timeseries data, return the last value. The raw flag indicates whether timeseries should be returned raw -- exactly as they are in the DB (a timeseries being a list of timeseries data objects, for example) or as a single python dictionary
entailment
def get_layout_as_string(layout): """ Take a dict or string and return a string. The dict will be json dumped. The string will json parsed to check for json validity. In order to deal with strings which have been json encoded multiple times, keep json decoding until a dict is retrieved or until a non-json structure is identified. """ if isinstance(layout, dict): return json.dumps(layout) if(isinstance(layout, six.string_types)): try: return get_layout_as_string(json.loads(layout)) except: return layout
Take a dict or string and return a string. The dict will be json dumped. The string will json parsed to check for json validity. In order to deal with strings which have been json encoded multiple times, keep json decoding until a dict is retrieved or until a non-json structure is identified.
entailment
def get_layout_as_dict(layout): """ Take a dict or string and return a dict if the data is json-encoded. The string will json parsed to check for json validity. In order to deal with strings which have been json encoded multiple times, keep json decoding until a dict is retrieved or until a non-json structure is identified. """ if isinstance(layout, dict): return layout if(isinstance(layout, six.string_types)): try: return get_layout_as_dict(json.loads(layout)) except: return layout
Take a dict or string and return a dict if the data is json-encoded. The string will json parsed to check for json validity. In order to deal with strings which have been json encoded multiple times, keep json decoding until a dict is retrieved or until a non-json structure is identified.
entailment
def get_username(uid,**kwargs): """ Return the username of a given user_id """ rs = db.DBSession.query(User.username).filter(User.id==uid).one() if rs is None: raise ResourceNotFoundError("User with ID %s not found"%uid) return rs.username
Return the username of a given user_id
entailment
def get_usernames_like(username,**kwargs): """ Return a list of usernames like the given string. """ checkname = "%%%s%%"%username rs = db.DBSession.query(User.username).filter(User.username.like(checkname)).all() return [r.username for r in rs]
Return a list of usernames like the given string.
entailment
def add_user(user, **kwargs): """ Add a user """ #check_perm(kwargs.get('user_id'), 'add_user') u = User() u.username = user.username u.display_name = user.display_name user_id = _get_user_id(u.username) #If the user is already there, cannot add another with #the same username. if user_id is not None: raise HydraError("User %s already exists!"%user.username) u.password = bcrypt.hashpw(str(user.password).encode('utf-8'), bcrypt.gensalt()) db.DBSession.add(u) db.DBSession.flush() return u
Add a user
entailment
def update_user_display_name(user,**kwargs): """ Update a user's display name """ #check_perm(kwargs.get('user_id'), 'edit_user') try: user_i = db.DBSession.query(User).filter(User.id==user.id).one() user_i.display_name = user.display_name return user_i except NoResultFound: raise ResourceNotFoundError("User (id=%s) not found"%(user.id))
Update a user's display name
entailment
def update_user_password(new_pwd_user_id, new_password,**kwargs): """ Update a user's password """ #check_perm(kwargs.get('user_id'), 'edit_user') try: user_i = db.DBSession.query(User).filter(User.id==new_pwd_user_id).one() user_i.password = bcrypt.hashpw(str(new_password).encode('utf-8'), bcrypt.gensalt()) return user_i except NoResultFound: raise ResourceNotFoundError("User (id=%s) not found"%(new_pwd_user_id))
Update a user's password
entailment
def get_user(uid, **kwargs): """ Get a user by ID """ user_id=kwargs.get('user_id') if uid is None: uid = user_id user_i = _get_user(uid) return user_i
Get a user by ID
entailment
def get_user_by_name(uname,**kwargs): """ Get a user by username """ try: user_i = db.DBSession.query(User).filter(User.username==uname).one() return user_i except NoResultFound: return None
Get a user by username
entailment
def get_user_by_id(uid,**kwargs): """ Get a user by username """ user_id = kwargs.get('user_id') try: user_i = _get_user(uid) return user_i except NoResultFound: return None
Get a user by username
entailment
def delete_user(deleted_user_id,**kwargs): """ Delete a user """ #check_perm(kwargs.get('user_id'), 'edit_user') try: user_i = db.DBSession.query(User).filter(User.id==deleted_user_id).one() db.DBSession.delete(user_i) except NoResultFound: raise ResourceNotFoundError("User (user_id=%s) does not exist"%(deleted_user_id)) return 'OK'
Delete a user
entailment
def add_role(role,**kwargs): """ Add a new role """ #check_perm(kwargs.get('user_id'), 'add_role') role_i = Role(name=role.name, code=role.code) db.DBSession.add(role_i) db.DBSession.flush() return role_i
Add a new role
entailment
def delete_role(role_id,**kwargs): """ Delete a role """ #check_perm(kwargs.get('user_id'), 'edit_role') try: role_i = db.DBSession.query(Role).filter(Role.id==role_id).one() db.DBSession.delete(role_i) except InvalidRequestError: raise ResourceNotFoundError("Role (role_id=%s) does not exist"%(role_id)) return 'OK'
Delete a role
entailment
def add_perm(perm,**kwargs): """ Add a permission """ #check_perm(kwargs.get('user_id'), 'add_perm') perm_i = Perm(name=perm.name, code=perm.code) db.DBSession.add(perm_i) db.DBSession.flush() return perm_i
Add a permission
entailment
def delete_perm(perm_id,**kwargs): """ Delete a permission """ #check_perm(kwargs.get('user_id'), 'edit_perm') try: perm_i = db.DBSession.query(Perm).filter(Perm.id==perm_id).one() db.DBSession.delete(perm_i) except InvalidRequestError: raise ResourceNotFoundError("Permission (id=%s) does not exist"%(perm_id)) return 'OK'
Delete a permission
entailment