def delete(self, nanopub: Nanopublication) -> dict:
        """
        Realiza la eliminacion de la nanopublicacion pasada
        """
        if nanopub != None:
            nanopub.delete()
            return {"status": "ok"}

        return {"status": "error"}
 def get_term_stats(
     self, protocol: str = None, users: list = None, tags: list = None
 ) -> list:
     """
     retorna las estadisticas de uso de de las terminos para el protocolo si este se envia,
     (en caso de no enviarlo se calcula de forma global)
     [\n
         "related":[
             { "term":<term>, "uris":[ {"label":<uri>,"count":<use> } ] }
         ],
         "used": [{ "label":<term>, "count":<number of use> }]
     \n]
     """
     not_step_tag_filter = [NanopublicationRepository.TAG_FILTER("step", False)]
     pipeline = NanopublicationRepository._with_protocol_filter(
         pipeline=[
             {"$unwind": "$components"},
             {
                 "$facet": {
                     "used": not_step_tag_filter + self.TERM_USED,
                     "related": not_step_tag_filter + self.TERM_RELATED,
                 }
             },
         ],
         protocol=protocol,
         tags=tags,
         users=users,
     )
     return list(Nanopublication.objects().aggregate(pipeline))
 def save(self, nanopub: Nanopublication) -> Nanopublication:
     """
     Realiza el almacenado de la nanopublicacion pasada
     """
     if nanopub != None:
         return nanopub.save()
     return None
Ejemplo n.º 4
0
 def __export_nanopublication(
     self,
     nanopub: Nanopublication,
     json: bool = False,
     rdf_format: str = None,
     temp_rdf: bool = False,
 ):
     if nanopub != None:
         if rdf_format != None and rdf_format != "trig":
             nanopub.rdf_raw = DBNanopub(
                 db_nano_pub=nanopub,
                 settings=self.settings,
                 from_db_rdf=(not temp_rdf)).serialize(rdf_format)
         return nanopub.to_json_map() if json else nanopub
     else:
         return {"error": "not-found"}
 def get_nanopub_by_artifact_code(self, artifact_code: str) -> Nanopublication:
     """
     retorna la primera Nanopublication relacionada al artifact_code pasado, este se relaciona
     con el PublicationInfo.artifact_code de la misma
     """
     db_nanopub = Nanopublication.objects(
         publication_info__artifact_code=artifact_code
     ).first()
     return self.__load_workflows_of_nanopub(nanopub=db_nanopub)
 def get_nanopubs_by_protocol(self, protocol: str) -> list:
     """
     retorna la lista de nanopublicaciones asociadas a la uri del protocolo pasado
     """
     return list(
         map(
             (lambda nanopub: self.__load_workflows_of_nanopub(nanopub=nanopub)),
             Nanopublication.objects(protocol=protocol),
         )
     )
    def __load_workflows_of_nanopub(self, nanopub: Nanopublication) -> list:
        """
        shortcut and validator to load associated workflows of passed nanopub
        """
        if self.workflows_repository != None and nanopub != None:
            workflows = self.workflows_repository.get_workflows_of_nanopub(
                nanopub_id=nanopub.id
            )
            nanopub.workflows = workflows

        return nanopub
    def get_nanopub(
        self, id: str, protocol=None, default: Nanopublication = None
    ) -> Nanopublication:
        """
        Realiza la consulta de la nanopublicacion asociada a los filtros pasados.
        en caso de la consulta no retornar un valor se retornara el default pasado
        """
        query = {"id": id}
        if protocol != None:
            query["protocol"] = protocol
        db_nanopub = Nanopublication.objects(**query).first()
        if db_nanopub != None:
            self.__load_workflows_of_nanopub(db_nanopub)
            return db_nanopub

        return default
 def get_nanopubs_by_author_stats(self, protocol: str = None):
     """
     returns the amount of annotations make for user in a protocol
     if this is sended otherwise returns for all protocols
     [\n
         { "label":<author>, "count":<number of nano publications> }
     \n]
     """
     pipeline = NanopublicationRepository._with_protocol_filter(
         pipeline=[
             {"$group": {"_id": "$author", "count": {"$sum": 1}}},
             {"$project": {"_id": 0, "label": "$_id", "count": "$count"}},
         ],
         protocol=protocol,
     )
     return list(Nanopublication.objects().aggregate(pipeline))
 def get_ontologies_stats(
     self, protocol: str = None, users: list = None, tags: list = None
 ) -> list:
     """
     retorna las estadisticas de uso de de las ontologias para el protocolo si este se envia,
     (en caso de no enviarlo se calcula de forma global)
     [\n
         { "label":<tag>, "count":<number of use> }
     \n]
     """
     pipeline = NanopublicationRepository._with_protocol_filter(
         pipeline=[{"$unwind": "$components"}] + self.GROUP_BY_ONTOLOGIES,
         protocol=protocol,
         users=users,
         tags=tags,
     )
     return list(Nanopublication.objects().aggregate(pipeline))
 def get_essential_stats(
     self, protocol: str = None, users: list = None, tags: list = None
 ):
     """
     retorna las estadisticas esenciales del protocolo si este se envia.
     (en caso de no enviarlo se calcula de forma global)
     esta incluye estadisticas de tags, ontologias, terminos
     [\n
         {
             "ontologies": [{ "label":<tag>, "count":<number of use> }],
             "tags": [{ "label":<tag>, "count":<number of use> }],
             "terms": {
                 "related":[
                     { "term":<term>, "uris":[ {"label":<uri>,"count":<use> } ] }
                 ],
                 "used": [{ "label":<term>, "count":<number of use> }]
             }
         }
     \n]
     """
     not_step_tag_filter = [NanopublicationRepository.TAG_FILTER("step", False)]
     pipeline = NanopublicationRepository._with_protocol_filter(
         pipeline=[
             {"$unwind": {"path": "$components"}},
             {
                 "$facet": {
                     "tags": NanopublicationRepository.GROUP_BY_TAGS(tags),
                     "ontologies": self.GROUP_BY_ONTOLOGIES,
                     "terms_used": not_step_tag_filter + self.TERM_USED,
                     "terms_related": not_step_tag_filter + self.TERM_RELATED,
                 }
             },
             {
                 "$project": {
                     "tags": 1,
                     "ontologies": 1,
                     "terms": {"used": "$terms_used", "related": "$terms_related"},
                 }
             },
         ],
         protocol=protocol,
         users=users,
         tags=tags,
     )
     return list(Nanopublication.objects().aggregate(pipeline))
 def all_nanopubs_metadata(self, size: int = 10) -> list:
     """
     returns all nanopubs metadata
     """
     pipeline = [
         { "$group": {"_id": "1", "count": {"$sum": 1}}},
         {
             "$project": {
                 "_id": 0,
                 "totalRecords": "$count",
                 "page": {"$literal": 1},
                 "size": {"$literal": size},
             }
         }
     ]
     empty = { "totalRecords": 0, "page": 1, "size": size }
     data = list(Nanopublication.objects().aggregate(pipeline))
     return data[0] if len(data) == 1 else empty
 def nanopubs_stats(
     self, protocol: str = None, users: list = None, tags: list = None, page: int = 1
 ) -> list:
     conditions = NanopublicationRepository._with_protocol_filter(
         pipeline=[{"$unwind": "$components"}],
         protocol=protocol,
         tags=tags,
         users=users,
     )
     projection = [
         {
             "$project": {
                 "_id": 0,
                 "id": "$components.id",
                 "text": "$components.term",
                 "tag": NanopublicationRepository.GENERIC_REDUCE("$components.tags"),
                 "text_position": {
                     "$concat": [
                         {"$toString": "$components.text_position.start"},
                         ",",
                         {"$toString": "$components.text_position.end"},
                     ]
                 },
                 "ontologies": NanopublicationRepository.GENERIC_REDUCE(
                     "$components.ontologies_info.url"
                 ),
                 "ontologies_label": NanopublicationRepository.GENERIC_REDUCE(
                     "$components.ontologies_info.label"
                 ),
                 "ontologies_term": NanopublicationRepository.GENERIC_REDUCE(
                     "$components.ontologies_info.term"
                 ),
             }
         }
     ]
     (empty, pipeline) = NanopublicationRepository._with_pagination(
         projection=projection, conditions=conditions, page=page, size=40
     )
     data = list(Nanopublication.objects().aggregate(pipeline))
     return data[0] if len(data) == 1 else empty
 def all_nanopubs(self, page: int = 1, size: int = 10, projection_mode:str = None) -> list:
     """
     returns all nanopubs with pagination
     """
     projection = []
     if projection_mode == "publication":
         projection = [
             {
                 "$project": {
                     "_id": 0,
                     "publication_info": "$publication_info"
                 }
             }
         ]
     (empty, pipeline) = NanopublicationRepository._with_pagination(
         projection=projection,
         conditions=[],
         page=page,
         size=size,
     )
     data = list(Nanopublication.objects().aggregate(pipeline))
     return data[0] if len(data) == 1 else empty
Ejemplo n.º 15
0
    def __update_nanopub_and_protocol(self, request: NanopubRequest) -> tuple:
        """
        realiza la actualizacion o creacion de la nanopublicacion y su protocolo realacionado, constuyendo esta a partir de
        los datos del Nanopubrequest\n
        (los cambios realizados se persistiran)\n

        retorna una tupla donde el primer parametro es el protocolo(Protocol) seguido de la nanopublicacion(Nanopublication)
        """
        clean_url = clean_url_with_settings(url=request.url,
                                            settings=self.settings)
        protocol = self.protocols_repo.get_protocol(
            uri=clean_url,
            default=Protocol.fromAnnotation(request.step,
                                            settings=self.settings),
        )
        nanopublication = self.nanopubs_repo.get_nanopub(
            protocol=protocol,
            id=request.id,
            default=Nanopublication(
                id=request.id,
                protocol=protocol,
                author=request.user,
                generatedAtTime=request.step.created,
            ),
        )

        # iterator for load bio_annotations
        def components_iterator(component, annotation):
            bio_annotations = list(
                map(
                    lambda ontology: BioPortalService.annotation_parse(ontology
                                                                       ),
                    self.assertion_strategy.bio_annotations(
                        annotation=annotation, full=True),
                ))
            component.rel_uris = list(
                map(lambda ontology: ontology["id"], bio_annotations))
            component.ontologies_info = list(
                map(
                    lambda ontology: OntologyInfo(
                        label=ontology["ontologyLabel"],
                        url=ontology["id"],
                        term=ontology["prefLabel"],
                        selector=ontology["selector"][0],
                    ),
                    bio_annotations,
                ))
            return component

        # aply new changes in nanopub
        nanopublication.components = NanopublicationComponent.fromAnnotations(
            annotations=request.annotations, iterator=components_iterator)
        # previous nanopub uri if exist
        previous_nanopub_uri = (nanopublication.publication_info.nanopub_uri
                                if nanopublication.publication_info != None
                                else None)
        # nanopublication remote registration
        rdf_nanopub = DBNanopub(db_nano_pub=nanopublication,
                                settings=self.settings)
        nanopublication.publication_info = self._publish_fairworksflows_nanopub(
            rdf_nanopub)
        # fetch remote rdf for local mirror
        if nanopublication.publication_info != None:
            rdf_nanopub = DBNanopub(
                db_nano_pub=nanopublication,
                settings=self.settings,
                np_client=self.nanopubremote,
            )
        nanopublication.rdf_raw = rdf_nanopub.serialize("trig")
        # persist data
        self.nanopubs_repo.save(nanopub=nanopublication)
        self.protocols_repo.save(protocol=protocol)
        # retraction of previous remote nanopublication
        if previous_nanopub_uri != None:
            self._retract_fairworksflows_nanopub(
                nanopub_uri=previous_nanopub_uri)

        return (protocol, nanopublication)