def test_annotation(self):
        sbol3.set_namespace('https://github.com/synbiodex/pysbol3')
        # Create custom annotation
        annotation_uri = 'http://example.org/boolean_property'
        annotation_value = 'foo'
        c = sbol3.Component('c1', sbol3.SBO_DNA)
        c.annotation = sbol3.TextProperty(c, annotation_uri,
                                          0, 1, [])
        c.annotation = annotation_value
        self.assertEqual(annotation_value, c.annotation)

        doc = sbol3.Document()
        doc.add(c)
        doc2 = sbol3.Document()
        with tempfile.TemporaryDirectory() as tmpdirname:
            test_file = os.path.join(tmpdirname, 'annotation.xml')
            doc.write(test_file, sbol3.RDF_XML)
            # Roundtrip
            doc2.read(test_file, sbol3.RDF_XML)

        # Recover annotation
        c = doc2.find('c1')
        c.annotation = sbol3.TextProperty(c, annotation_uri,
                                          0, 1, [])
        self.assertEqual(annotation_value, c.annotation)
    def dataSource(self):
        self.obj.wasDerivedFrom = self.cell_val
        if "pubmed.ncbi.nlm.nih.gov/" in self.cell_val:
            if 'obo' not in self.doc_pref_terms:
                self.doc.addNamespace('http://purl.obolibrary.org/obo/', 'obo')
                self.doc_pref_terms.append('obo')

            self.obj.OBI_0001617 = sbol3.TextProperty(
                self.obj, 'http://purl.obolibrary.org/obo/OBI_0001617', 0, 1,
                [])
            self.obj.OBI_0001617 = self.cell_val.split(".gov/")[1].replace(
                "/", "")
Exemple #3
0
 def __init__(self, identity,
              *, information: Optional[str, list[str]] = None,
              namespace: str = None,
              attachments: list[str] = None,
              name: str = None, description: str = None,
              derived_from: list[str] = None,
              generated_by: list[str] = None,
              measures: list[sbol3.SBOLObject] = None) -> None:
     super().__init__(identity=identity,
                      type_uri=TextPropertyExtension.TYPE_URI,
                      namespace=namespace,
                      attachments=attachments, name=name,
                      description=description, derived_from=derived_from,
                      generated_by=generated_by, measures=measures)
     self.information = sbol3.TextProperty(self,
                                           TextPropertyExtension.TPE_INFO_URI,
                                           0, math.inf,
                                           initial_value=information)
        def __init__(self, *args, **kwargs):
            base_kwargs = {
                kw: val
                for kw, val in kwargs.items() if kw not in property_names
            }
            if 'type_uri' not in base_kwargs:
                base_kwargs['type_uri'] = CLASS_URI
            Super.__init__(self, *args, **base_kwargs)
            if 'http://sbols.org/v3#' in superclass_uri and not superclass_uri == SBOL_TOP_LEVEL and not superclass_uri == SBOL_IDENTIFIED:
                if class_is_top_level:
                    self._rdf_types.append(SBOL_TOP_LEVEL)
                else:
                    self._rdf_types.append(SBOL_IDENTIFIED)

            # Initialize associative properties
            for property_uri in associative_properties:
                property_name = property_uri_to_name[property_uri]
                lower_bound, upper_bound = property_cardinalities[property_uri]
                self.__dict__[property_name] = sbol.ReferencedObject(
                    self, property_uri, lower_bound, upper_bound)

            # Initialize compositional properties
            for property_uri in compositional_properties:
                property_name = property_uri_to_name[property_uri]
                lower_bound, upper_bound = property_cardinalities[property_uri]
                self.__dict__[property_name] = sbol.OwnedObject(
                    self, property_uri, lower_bound, upper_bound)

            # Initialize datatype properties
            for property_uri in datatype_properties:
                # TODO: Cache query information outside of constructor
                property_name = property_uri_to_name[property_uri]
                # Get the datatype of this property
                datatypes = property_datatypes[property_uri]
                if len(datatypes) == 0:
                    continue
                if len(datatypes
                       ) > 1:  # This might indicate an error in the ontology
                    raise

                # Get the cardinality of this datatype property
                lower_bound, upper_bound = property_cardinalities[property_uri]
                if datatypes[0] == 'http://www.w3.org/2001/XMLSchema#string':
                    self.__dict__[property_name] = sbol.TextProperty(
                        self, property_uri, lower_bound, upper_bound)
                elif datatypes[
                        0] == 'http://www.w3.org/2001/XMLSchema#integer':
                    self.__dict__[property_name] = sbol.IntProperty(
                        self, property_uri, lower_bound, upper_bound)
                elif datatypes[
                        0] == 'http://www.w3.org/2001/XMLSchema#boolean':
                    self.__dict__[property_name] = sbol.BooleanProperty(
                        self, property_uri, lower_bound, upper_bound)
                elif datatypes[0] == 'http://www.w3.org/2001/XMLSchema#anyURI':
                    self.__dict__[property_name] = sbol.URIProperty(
                        self, property_uri, lower_bound, upper_bound)
                elif datatypes[
                        0] == 'http://www.w3.org/2001/XMLSchema#dateTime':
                    self.__dict__[property_name] = sbol.DateTimeProperty(
                        self, property_uri, lower_bound, upper_bound)

            for kw, val in kwargs.items():
                if kw == 'type_uri':
                    continue
                if kw in self.__dict__:
                    try:
                        self.__dict__[kw].set(val)
                    except:
                        pass
    def switch(self, sbol_term):
        """Switch statement that calls a different method based on the
        sbol_term. For example if the sbol_term is sbh_alteredSequence
        then the function sbh_alteredSequence() will be run. If there is
        no function with a name equal to the sbol_term then the add_new method
        is run.

        Args:
            sbol_term (str): String indicating the method of processing
                    required by the cell_value

        Returns:
            Nothing is returned but the componentDefinition and sbol doc
            are updated according to the sbol_term and cell_value
        """
        self.sbol_term_pref = sbol_term.split("_", 1)[0]
        try:
            self.sbol_term_suf = sbol_term.split("_", 1)[1]
        except IndexError:
            raise ValueError(
                f"The SBOL Term '{sbol_term}' (sheet name: {self.sheet}) does not appear to have an underscore"
            )

        if self.parental_lookup:
            # switches the object being worked on
            self.obj = self.obj_dict[self.cell_val]['object']
            self.cell_val = self.obj_uri

        # if not applicable then do nothing
        if sbol_term == "Not_applicable":
            pass

        # if a special function has been defined below then do something
        elif hasattr(self, self.sbol_term_suf):
            return getattr(self, self.sbol_term_suf)()

        # if it is an sbol term use standard pySBOL implementation
        # unless it is a top level object in which case the standard
        # implementations don't work
        elif self.sbol_term_pref == "sbol":
            if hasattr(self.obj, self.sbol_term_suf):
                # if the attribute is a list append the new value
                if isinstance(getattr(self.obj, self.sbol_term_suf), list):
                    current = getattr(self.obj, self.sbol_term_suf)
                    # if the cell_val is a list append the whole list
                    if isinstance(self.cell_val, list):
                        setattr(self.obj, self.sbol_term_suf,
                                current + self.cell_val)
                    else:
                        setattr(self.obj, self.sbol_term_suf,
                                current + [self.cell_val])
                elif isinstance(getattr(self.obj, self.sbol_term_suf),
                                sbol3.refobj_property.ReferencedObjectList):
                    getattr(getattr(self.obj, self.sbol_term_suf),
                            'append')(self.cell_val)
                else:
                    # no iteration over list as else suggests that the property
                    # can't have multiple values
                    setattr(self.obj, self.sbol_term_suf, self.cell_val)
            else:
                raise ValueError(
                    f'This SBOL object ({type(self.obj)}) has no attribute {self.sbol_term_suf} (sheet:{self.sheet}, row:{self.sht_row}, col:{self.sht_col})'
                )

        else:
            # logging.warning(f'This sbol term ({self.sbol_term}) has not yet been implemented so it has been added via the default method')
            # define a new namespace if needed
            if self.sbol_term_pref not in self.doc_pref_terms:
                self.doc.addNamespace(self.namespace_url, self.sbol_term_pref)
                self.doc_pref_terms.append(self.sbol_term_pref)

            # if type is uri make it a uri property
            if self.col_type == "URI":
                # * allows multiple instance of this property
                if not hasattr(self.obj, self.sbol_term_suf):
                    setattr(
                        self.obj, self.sbol_term_suf,
                        sbol3.URIProperty(
                            self.obj,
                            f'{self.namespace_url}{self.sbol_term_suf}',
                            '0',
                            '*',
                            initial_value=[self.cell_val]))
                else:
                    if not isinstance(self.cell_val, list):
                        self.cell_val = [self.cell_val]
                    current = getattr(self.obj, self.sbol_term_suf)
                    setattr(self.obj, self.sbol_term_suf,
                            list(current) + self.cell_val)

            # otherwise implement as text property
            else:
                # * allows multiple instance of this property
                if not hasattr(self.obj, self.sbol_term_suf):
                    setattr(
                        self.obj, self.sbol_term_suf,
                        sbol3.TextProperty(
                            self.obj,
                            f'{self.namespace_url}{self.sbol_term_suf}',
                            '0',
                            '*',
                            initial_value=str(self.cell_val)))
                else:
                    if not isinstance(self.cell_val, list):
                        self.cell_val = [self.cell_val]
                    current = getattr(self.obj, self.sbol_term_suf)
                    setattr(self.obj, self.sbol_term_suf,
                            list(current) + self.cell_val)
    def switch(self, rowobj, sbol_term, sbol_version):
        if sbol_version == 2:
            self.func_list = self.func_list2
            exutil = exutil2
        elif sbol_version == 3:
            self.func_list = self.func_list3
            exutil = exutil3
        else:
            raise ValueError(
                f"SBOL Version ({sbol_version}) given to switch has not been implemented yet"
            )

        # split sbol term into prefix and suffix
        self.sbol_term = sbol_term
        self.sbol_term_pref = sbol_term.split("_", 1)[0]
        try:
            self.sbol_term_suf = sbol_term.split("_", 1)[1]
        except IndexError:
            raise ValueError(
                f"The SBOL Term '{sbol_term}' (sheet name: {self.sheet}) does not appear to have an underscore"
            )

        # if not applicable then do nothing
        if sbol_term == "Not_applicable":
            pass

        # if a special function has been defined in excel-sbol-utils then use that
        elif self.sbol_term_suf in self.func_list:
            return getattr(exutil, self.sbol_term_suf)(rowobj)

        # if it is an sbol term use standard pySBOL implementation
        # unless it is a top level object in which case the standard
        # implementations don't work
        elif self.sbol_term_pref == "sbol":

            for col in rowobj.col_cell_dict:

                cell_val = rowobj.col_cell_dict[col]

                parental_lookup = rowobj.term_coldef_df[
                    rowobj.term_coldef_df['Column Name'] ==
                    col]['Parent Lookup']
                if parental_lookup.values[0]:
                    # switches the object being worked on
                    rowobj.obj = rowobj.obj_dict[cell_val]['object']
                    cell_val = rowobj.obj_uri

                if hasattr(rowobj.obj, self.sbol_term_suf):
                    # if the attribute is a list append the new value
                    if isinstance(getattr(rowobj.obj, self.sbol_term_suf),
                                  list):
                        current = getattr(rowobj.obj, self.sbol_term_suf)
                        # if the col_cell_dict has multiple columns append each

                        # if cell_val is a dict then mcol must have been given
                        if isinstance(cell_val, dict):
                            raise TypeError(
                                f"A multicolumn value was unexpectedly given for sheet:{rowobj.sheet}, row:{rowobj.sht_row}, sbol term :{self.sbol_term}, sbol term dict: {rowobj.col_cell_dict}"
                            )
                        # if the cell_val is a list append the whole list
                        elif isinstance(cell_val, list):
                            setattr(rowobj.obj, self.sbol_term_suf,
                                    current + cell_val)
                        # otherwise append as a list object
                        else:
                            setattr(rowobj.obj, self.sbol_term_suf,
                                    current + [cell_val])

                    # if type sbol list then add by special append
                    # rather than regular list append
                    elif isinstance(
                            getattr(rowobj.obj, self.sbol_term_suf),
                            sbol3.refobj_property.ReferencedObjectList):

                        # if cell_val is a dict then mcol must have been given
                        if isinstance(cell_val, dict):
                            raise TypeError(
                                f"A multicolumn value was unexpectedly given for sheet:{rowobj.sheet}, row:{rowobj.sht_row}, sbol term :{self.sbol_term}, sbol term dict: {rowobj.col_cell_dict}"
                            )
                        # else should be fine to append
                        else:
                            getattr(getattr(rowobj.obj, self.sbol_term_suf),
                                    'append')(cell_val)

                    else:

                        # no iteration over list as else suggests that the property
                        # can't have multiple values

                        setattr(rowobj.obj, self.sbol_term_suf, cell_val)
                else:
                    raise ValueError(
                        f'This SBOL object ({type(rowobj.obj)}) has no attribute {self.sbol_term_suf} (sheet:{rowobj.sheet}, row:{rowobj.sht_row}, sbol term dict:{rowobj.col_cell_dict})'
                    )

        else:
            # logging.warning(f'This sbol term ({self.sbol_term}) has not yet been implemented so it has been added via the default method')
            # define a new namespace if needed
            for col in rowobj.col_cell_dict:
                cell_val = rowobj.col_cell_dict[col]
                col_coldef_df = rowobj.term_coldef_df[
                    rowobj.term_coldef_df['Column Name'] == col]

                if len(col_coldef_df) == 0:
                    raise TypeError(
                        f"A multicolumn value was unexpectedly given for sheet:{rowobj.sheet}, row:{rowobj.sht_row}, sbol term :{self.sbol_term}, sbol term dict: {rowobj.col_cell_dict}"
                    )

                parental_lookup = col_coldef_df['Parent Lookup'].values[0]
                if parental_lookup:
                    # switches the object being worked on
                    rowobj.obj = rowobj.obj_dict[cell_val]['object']
                    cell_val = rowobj.obj_uri

                namespace_url = col_coldef_df['Namespace URL'].values[0]
                if self.sbol_term_pref not in rowobj.doc_pref_terms:
                    rowobj.doc.addNamespace(namespace_url, self.sbol_term_pref)
                    rowobj.doc_pref_terms.append(self.sbol_term_pref)

                col_type = col_coldef_df['Type'].values[0]
                # if type is uri make it a uri property
                if col_type == "URI":
                    # * allows multiple instance of this property
                    if not hasattr(rowobj.obj, self.sbol_term_suf):
                        if sbol_version == 2:
                            setattr(
                                rowobj.obj, self.sbol_term_suf,
                                sbol2.URIProperty(
                                    rowobj.obj,
                                    f'{namespace_url}{self.sbol_term_suf}',
                                    '0', '*', []))
                            setattr(rowobj.obj, self.sbol_term_suf, cell_val)
                        elif sbol_version == 3:
                            setattr(
                                rowobj.obj, self.sbol_term_suf,
                                sbol3.URIProperty(
                                    rowobj.obj,
                                    f'{namespace_url}{self.sbol_term_suf}',
                                    '0',
                                    '*',
                                    initial_value=[cell_val]))
                    else:
                        if not isinstance(cell_val, list):
                            cell_val = [cell_val]
                        current = getattr(rowobj.obj, self.sbol_term_suf)
                        setattr(rowobj.obj, self.sbol_term_suf,
                                list(current) + cell_val)

                # otherwise implement as text property
                else:
                    # * allows multiple instance of this property
                    if not hasattr(rowobj.obj, self.sbol_term_suf):
                        if sbol_version == 2:
                            setattr(
                                rowobj.obj, self.sbol_term_suf,
                                sbol2.TextProperty(
                                    rowobj.obj,
                                    f'{namespace_url}{self.sbol_term_suf}',
                                    '0', '*'))
                            setattr(rowobj.obj, self.sbol_term_suf,
                                    str(cell_val))
                        elif sbol_version == 3:
                            setattr(
                                rowobj.obj, self.sbol_term_suf,
                                sbol3.TextProperty(
                                    rowobj.obj,
                                    f'{namespace_url}{self.sbol_term_suf}',
                                    '0',
                                    '*',
                                    initial_value=str(cell_val)))
                    else:
                        if not isinstance(cell_val, list):
                            cell_val = [cell_val]
                        current = getattr(rowobj.obj, self.sbol_term_suf)
                        setattr(rowobj.obj, self.sbol_term_suf,
                                list(current) + cell_val)