parse an ontology file

@param oboFile
@throws IOException
@throws IOException
183286
public void parseOBO(BufferedReader oboFile) throws IOException{

		String line;
		String currentStanza;

		while ((line = oboFile.readLine()) != null) {
			if (line.length() == 0)
				continue;

			if ( line.charAt(0) == '[') {
				if (line.charAt(line.length() - 1) != ']')
					throw new IOException("Unclosed stanza: \"" + line + "\"" );
				String stanzaname = line.substring(1, line.length() - 1);
				if (stanzaname.length() < 1)
					throw new IOException("Empty stanza: \"" +line+"\"");
				currentStanza = stanzaname;

				//logger.info("stanza: {}", currentStanza);
				triggerNewStanza(currentStanza);

			} else {
				// a content line
				SOPair pair;

				pair = unescape(line, ':', 0, true);

				//logger.info(pair);
				String name = pair.str;
				int lineEnd = findUnescaped(line, '!', 0, line.length(), true);
				if (lineEnd == -1)
					lineEnd = line.length();

				// find nested values
				NestedValue nv = null;

				int trailingStartIndex = -1;
				int trailingEndIndex = -1;
				for (int i = lineEnd - 1; i >= 0; i--) {
					if (Character.isWhitespace(line.charAt(i))) {
						// keep going until we see non-whitespace
					} else if (line.charAt(i) == '}') {
						// if the first thing we see is a closing brace,
						// we have a trailing modifier
						if (i >= 1 && line.charAt(i - 1) == '\\')
							continue;
						trailingEndIndex = i;
						break;
					} else
						break;
				}

				if (trailingEndIndex != -1) {
					for (int i = trailingEndIndex - 1; i >= 0; i--) {
						if (line.charAt(i) == '{') {
							if (i >= 1 && line.charAt(i - 1) == '\\')
								continue;
							trailingStartIndex = i + 1;
						}
					}
				}

				int valueStopIndex;
				if (trailingStartIndex == -1 && trailingEndIndex != -1)
					throw new IOException("Unterminated trailing modifier. " + line);
				else if (trailingStartIndex != -1) {
					valueStopIndex = trailingStartIndex - 1;
					String trailing = line.substring(trailingStartIndex,
							trailingEndIndex).trim();
					nv = new NestedValue();
					getNestedValue(nv, trailing, 0);
				} else
					valueStopIndex = lineEnd;

				String value = line.substring(pair.index + 1, valueStopIndex).trim();
				/*
				 * if (nv != null) logger.warn("nv = "+nv+", value =
				 * |"+value+"|");
				 */
				if (value.length() == 0)
					throw new IOException("Tag found with no value "+ line);

				if ( isSynonym(name)){
					Synonym synonym = parseSynonym(name,value);
					triggerNewSynonym(synonym);
				} else {
					//logger.info("new key:" + name + " " + value);
					triggerNewKey(name,value);
				}
				//logger.info("parsed key: " + name +" value: " + value + " nv: " + nv);



			}
		}
	}
1040492
def main():
    
    parser = argparse.ArgumentParser(description='Wrapper for obographs assocmodel library'
                                                 """
                                                 By default, ontologies and assocs are cached locally and synced from a remote sparql endpoint
                                                 """,
                                     formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument('-r', '--resource', type=str, required=False,
                        help='Name of ontology')
    parser.add_argument('-f', '--file', type=str, required=False,
                        help='Name of input file for associations - currently GAF is assumed')
    parser.add_argument('-F', '--format', type=str, required=False,
                        help='Format of assoc file. One of GAF, GPAD or HPOA')
    parser.add_argument('-o', '--outfile', type=str, required=False,
                        help='Path to output file')
    parser.add_argument("--report-md", type=str, required=False, dest="report_md",
                        help="Path to report markdown file")
    parser.add_argument("--report-json", type=str, required=False, dest="report_json",
                        help="Path to report JSON file")
    parser.add_argument('-t', '--to', type=str, required=False,
                        help='Output to (tree, dot, ...)')
    parser.add_argument("--filter-out", nargs="+", required=False, default=[], metavar="EVIDENCE",
                        help="List of any evidence codes to filter out of the GAF. E.G. --filter-out IEA IMP")
    parser.add_argument("--filtered-file", required=False, default=None, metavar="FILTERED_FILE",
                        help="File to write the filtered out evidence GAF to")
    parser.add_argument('-T', '--taxon', nargs='*', required=False,
                        help='valid taxon (NCBITaxon ID) - validate against this')
    parser.add_argument('--subject_prefix', nargs='*', required=False,
                        help='E.g PomBase - validate against this')
    parser.add_argument('--object_prefix', nargs='*', required=False,
                        help='E.g GO - validate against this')
    parser.add_argument('-v', '--verbosity', default=0, action='count',
                        help='Increase output verbosity')


    subparsers = parser.add_subparsers(dest='subcommand', help='sub-command help')

    parser_n = subparsers.add_parser('validate', help='Validate associations')
    parser_n.set_defaults(function=validate_assocs)

    parser_n = subparsers.add_parser('filter', help='Filter associations')
    parser_n.set_defaults(function=filter_assocs)

    parser_n = subparsers.add_parser('convert', help='Convert associations')
    parser_n.set_defaults(function=convert_assocs)
    parser_n.add_argument('-t', '--to', type=str, required=True,
                          help='Format to convert to')

    parser_n = subparsers.add_parser('map2slim', help='Map to a subset/slim')
    parser_n.set_defaults(function=map2slim)
    parser_n.add_argument('-p', '--properties', nargs='*', type=str, default=['subClassOf', 'BFO:0000050'],
                          help='Properties')
    parser_n.add_argument('-s', '--subset', type=str, required=True,
                          help='subset (e.g. map2slim)')

    args = parser.parse_args()

    if args.verbosity >= 2:
        logging.basicConfig(level=logging.DEBUG)
    elif args.verbosity == 1:
        logging.basicConfig(level=logging.INFO)
    else:
        logging.basicConfig(level=logging.WARNING)

    logging.info("Welcome!")

    handle = args.resource

    # Ontology Factory
    ofactory = OntologyFactory()
    logging.info("Creating ont object from: {} {}".format(handle, ofactory))
    ont = ofactory.create(handle)
    logging.info("ont: {}".format(ont))

    func = args.function

    # Upper case all evidence codes
    args.filter_out = [code.upper() for code in args.filter_out]

    # set configuration
    filtered_evidence_file = open(args.filtered_file, "w") if args.filtered_file else None
    config = assocparser.AssocParserConfig(
        valid_taxa=args.taxon,
        ontology=ont,
        class_idspaces=args.object_prefix,
        entity_idspaces=args.subject_prefix,
        filter_out_evidence=args.filter_out,
        filtered_evidence_file=filtered_evidence_file
    )
    p = None
    fmt = None
    if args.format is None:
        fmt = 'gaf'
    else:
        fmt = args.format.lower()

    # TODO: use a factory
    if fmt == 'gaf':
        p = GafParser(dataset=args.file)
    elif fmt == 'gpad':
        p = GpadParser()
    elif fmt == 'hpoa':
        p = HpoaParser()
    elif fmt == "gpi":
        p = entityparser.GpiParser()
        func = validate_entity

    p.config = config

    outfh = None
    if args.outfile is not None:
        two_mb = 2097152
        outfh = open(args.outfile, "w", buffering=two_mb)
    func(ont, args.file, outfh, p, args)
    if filtered_evidence_file:
        filtered_evidence_file.close()

    if outfh is not None:
        outfh.close()

    if args.report_md is not None:
        report_md = open(args.report_md, "w")
        report_md.write(p.report.to_markdown())
        report_md.close()
    if args.report_json is not None:
        report_json = open(args.report_json, "w")
        report_json.write(json.dumps(p.report.to_report_json(), indent=4))
        report_json.close()
    if not (args.report_md or args.report_json):
        print(p.report.to_markdown())
507215
public static Package parse(File file) throws IOException
        {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(file, Package.class);
        }
349432
def parseFile(self, fil) :
		""""""
		f = open(fil)
		self.parseStr(f.read())
		f.close()
595314
public BinarySparseDataset parse(File file) throws IOException, ParseException {
        String name = file.getPath();
        return parse(name, new FileInputStream(file));
    }
626957
public static void store(Explanation<OWLAxiom> explanation, OutputStream os) throws IOException {
        try {
            OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
            OWLOntology ontology = manager.createOntology(explanation.getAxioms());
            OWLDataFactory df = manager.getOWLDataFactory();
            OWLAnnotationProperty entailmentMarkerAnnotationProperty = df.getOWLAnnotationProperty(ENTAILMENT_MARKER_IRI);
            OWLAnnotation entailmentAnnotation = df.getOWLAnnotation(entailmentMarkerAnnotationProperty, df.getOWLLiteral(true));
            OWLAxiom annotatedEntailment = explanation.getEntailment().getAnnotatedAxiom(Collections.singleton(entailmentAnnotation));
            manager.addAxiom(ontology, annotatedEntailment);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(os);
            OWLXMLDocumentFormat justificationOntologyFormat = new OWLXMLDocumentFormat();
            manager.saveOntology(ontology, justificationOntologyFormat, bufferedOutputStream);
        }
        catch (OWLOntologyStorageException | OWLOntologyCreationException e) {
            throw new RuntimeException(e);
        }

    }
1147108
def ontology2df(self):
        ''''''

        if isinstance(self.path, str) or isinstance(self.path, p):
            self.path = str(self.path)
            filetype = p(self.path).suffix
            if filetype == '.json':
                self.g = None
                try:
                    records = open_json(self.path)
                    return pd.DataFrame(records)
                except:
                    exit('Json file is not in records format.')
            if filetype == '.pickle':
                self.g = None
                return pickle.load(open(self.path, 'rb'))
            elif filetype == '.ttl' or filetype == '.rdf':
                self.g = rdflib.Graph()
                self.g.parse(self.path, format='turtle')
                return self.get_sparql_dataframe()
            elif filetype == '.nt':
                self.g = rdflib.Graph()
                self.g.parse(self.path, format='nt')
                return self.get_sparql_dataframe()
            elif filetype == '.owl' or filetype == '.xrdf':
                self.g = rdflib.Graph()
                try:
                    self.g.parse(self.path, format='xml')
                except:
                    # some owl formats are more rdf than owl
                    self.g.parse(self.path, format='turtle')
                return self.get_sparql_dataframe()
            else:
                exit('Format options: owl, ttl, df_pickle, rdflib.Graph()')
            try:
                return self.get_sparql_dataframe()
                self.path = None
            except:
                exit('Format options: owl, ttl, df_pickle, rdflib.Graph()')

        elif isinstance(self.g, rdflib.graph.Graph):
            self.path = None
            return self.get_sparql_dataframe()

        else:
            exit('Obj given is not str, pathlib obj, or an rdflib.Graph()')
430802
public void convertToJsonld(InputStream in, OutputStream os)
			throws IOException {
		
		File inputProcessedFile = preProcessFile(in);
		LOG.info("OWl File processed successfully ");
		
		// print current time
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		LOG.info("Conversion RDF to JSONLD started "
				+ sdf.format(Calendar.getInstance().getTime()));

		// create an empty model
		Model modelJena = ModelFactory.createDefaultModel();
		InputStream internalInputStream = new FileInputStream(inputProcessedFile);
		// read the RDF/XML file
		RDFDataMgr.read(modelJena, internalInputStream, Lang.RDFXML);
		LOG.info("Read into Model finished " + sdf.format(Calendar.getInstance().getTime()));

		try { //close quietly and delete the temp. input file
			internalInputStream.close();
			inputProcessedFile.delete();
		} catch(Exception e) {}

		RDFDataMgr.write(os, modelJena, Lang.JSONLD);
		LOG.info("Conversion RDF to JSONLD finished " + sdf.format(Calendar.getInstance().getTime()));
		LOG.info(" JSONLD file " + " is written successfully.");

		try { //close, flush quietly
			os.close();
		} catch(Exception e) {}
	}
605617
def _get_ontology(ontology):
    
    onto_name = onto_path = onto_url = None

    # first assume we got the path to the file
    if os.path.exists(ontology):
        onto_name = os.path.split(os.path.abspath(ontology))[1]
        onto_path = os.path.abspath(ontology)
        onto_url = ""
    else:
        # if not, try to find it in a known locations
        discovered_file = _discover_ontology(ontology)
        if discovered_file:
            onto_name = os.path.split(discovered_file)[1]
            onto_path = discovered_file

            x = ontology.lower()
            if "http:" in x or "https:" in x or "ftp:" in x or "file:" in x:
                onto_url = ontology
                onto_path = _get_remote_ontology(onto_url)
            else:
                onto_url = ""

    return (onto_name, onto_path, onto_url)
1089456
private au.csiro.ontology.Node getNode(OWLClass oc) {
        final Object id = getId(oc);

        final au.csiro.ontology.Node n;

        if(id instanceof String) {
            n = getTaxonomy().getNode((String)id);
        } else if(NamedConcept.TOP.equals(id)) {
            n = getTaxonomy().getTopNode();
        } else if(NamedConcept.BOTTOM.equals(id)) {
            n = getTaxonomy().getBottomNode();
        } else {
            throw new RuntimeException("Unexpected id "+id);
        }

        return n;
    }
719324
def parse_owl_rdf(iri):
    
    g = nx.DiGraph(IRI=iri)
    o = Ontospy(iri)

    for cls in o.classes:
        g.add_node(cls.locale, type='Class')

        for parent in cls.parents():
            g.add_edge(cls.locale, parent.locale, type='SubClassOf')

        for instance in cls.instances():
            _, frag = urldefrag(instance)
            g.add_edge(frag, cls.locale, type='ClassAssertion')

    return g
672401
public static Schema parseSchemaFromFile(Path filePath, FileSystem fs) throws IOException {
    Preconditions.checkArgument(fs.exists(filePath), filePath + " does not exist");

    try (FSDataInputStream in = fs.open(filePath)) {
      return new Schema.Parser().parse(in);
    }
  }
568324
def parse_ontology(self):
        """"""
        start = time.clock()
        log.info("Parsing ontology file for %s" % self.__class__.__name__)
        for subj, pred, obj in self._schema_nodes():
            if subj not in self.attributes_by_class:
                if obj == rt.URIRef(self.lexicon['class']) and \
                        pred == rt.URIRef(self.lexicon['type']):
                    self.attributes_by_class[subj] = []

            leaves = [(subj, pred, obj)]
            if type(obj) == rt.BNode:
                leaves = deepest_node((subj, pred, obj), self.graph)

            for s, p, o in leaves:
                if o not in self.attributes_by_class:
                    self.attributes_by_class[o] = []
                if pred == rt.URIRef(self.lexicon['domain']):
                    self.attributes_by_class[o].append(subj)
        if not self.attributes_by_class:
            log.info("No nodes found in ontology")
        log.info("Ontology parsing complete in {}".format(
            (time.clock() - start) * 1000))
636318
private OWLOntology loadOntologyFromURI(URI uri) throws OWLIOException
    {
        try
        {
            return owlOntologyManager.loadOntologyFromOntologyDocument(IRI.create(uri));
        } catch (OWLOntologyCreationException ex)
        {
            throw new OWLIOException(ioErrorMsg, ex);
        }
    }
312572
def get_ontology(self, id=None, uri=None, match=None):
        

        if not id and not uri and not match:
            return None

        if type(id) == type("string"):
            uri = id
            id = None
            if not is_http(uri):
                match = uri
                uri = None
        if match:
            if type(match) != type("string"):
                return []
            res = []
            for x in self.all_ontologies:
                if match.lower() in x.uri.lower():
                    res += [x]
            return res
        else:
            for x in self.all_ontologies:
                if id and x.id == id:
                    return x
                if uri and x.uri.lower() == uri.lower():
                    return x
            return None
779327
public void parseFile(File file, boolean utterancePerDoc) {
        try {
            // Build an xml document.
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(file);

            // Extract all utterances.
            NodeList utterances = doc.getElementsByTagName("u");
            StringBuilder fileBuilder = new StringBuilder();
            for (int i = 0; i < utterances.getLength(); ++i) {
                // Extract all words from the utterance
                Element item = (Element) utterances.item(i);
                NodeList words = item.getElementsByTagName("w");
                StringBuilder utteranceBuilder = new StringBuilder();

                // Iterate over the words and get just the word text.
                List<String> wordsInUtterance =
                    new ArrayList<String>(words.getLength());
                for (int j = 0; j < words.getLength(); ++j) {
                    // Get the part of speech tag.
                    Element wordNode = (Element) words.item(j);
                    NodeList posNodeList = wordNode.getElementsByTagName("pos");
                    String word = wordNode.getFirstChild().getNodeValue();
                    if (posNodeList.getLength() > 0) {
                        Node posNode = 
                            posNodeList.item(0).getFirstChild().getFirstChild();
                        String pos = posNode.getNodeValue();
                        posTags.put(word, pos);
                        if (appendPosTags)
                            word += "-" + pos;
                    }
                    wordsInUtterance.add(word);
                }

                // Each of the <a> nodes contains additional information about
                // the currnet utterances.  This may be syntactic information,
                // comments on the scene, descriptions of the action, or
                // clarification by the observer.  For all comments but the
                // syntactic, use the comment text to create new pseudo
                // utterances by combining tokens from the utterance with
                // pseudo-tokens in the comment.  The pseudo-tokens have a
                // "-GROUNDING" suffix which distiguishes them from tokens
                // actually present in the uttered speech.
                NodeList auxNodes = item.getElementsByTagName("a");
                List<String> augmentedUtterances = new LinkedList<String>();
                if (generateAugmented) {
                    for (int j = 0; j < auxNodes.getLength(); ++j) {
                        // Get any comment for the utterance
                        Node n = auxNodes.item(j);
                        String auxNodeType = n.getAttributes().
                            getNamedItem("type").getNodeValue();

                        // Get only those nodes that contain comments or
                        // descriptions on the utterance that may be used to
                        // ground the words being referred to.
                        if (auxNodeType.equals("action")
                            || auxNodeType.equals("actions")
                            || auxNodeType.equals("addressee")
                            || auxNodeType.equals("comments")
                            || auxNodeType.equals("explanation")
                            || auxNodeType.equals("gesture")
                            || auxNodeType.equals("happening")
                            || auxNodeType.equals("situation")) {
                            
                            String commentOnUtterance = 
                                n.getFirstChild().getNodeValue();
                            // Use the iterator factory to tokenize in the event
                            // that the user has specified some form of token
                            // filtering
                            Iterator<String> tokenIter = 
                                IteratorFactory.tokenize(
                                        new BufferedReader(
                                            new StringReader(
                                                commentOnUtterance)));
                            // For each of the tokens in the additional
                            // information, create a pseudo-utterance using a
                            // word from the actual utterance and an
                            // grounding-token
                            while (tokenIter.hasNext()) {
                                String token = tokenIter.next();
                                for (String word : wordsInUtterance) {
                                    augmentedUtterances.add(word + " "
                                        + token + "-GROUNDING");
                                }
                            }
                        }
                    }
                }
                    
                // Write the utterance if an utterance is a document.
                for (Iterator<String> it = wordsInUtterance.iterator(); 
                         it.hasNext(); ) {
                    utteranceBuilder.append(it.next());
                    if (it.hasNext())
                        utteranceBuilder.append(" ");
                }
                String utterance = utteranceBuilder.toString();
                if (utterancePerDoc) {
                    print(utterance);
                    // Print all the psuedo utterances constructed from the
                    // comments
                    for (String aug : augmentedUtterances)
                        print(aug);
                }
                else {  // otherwise save the utterance.
                    fileBuilder.append(utterance);
                    if (separateByPeriod)
                        fileBuilder.append(".");
                    fileBuilder.append(" ");

                    // Print all the psuedo utterances constructed from the
                    // comments.  Unlike the utterances, print these as separate
                    // documents to avoid having them register as co-occurrences
                    // with other utterances.
                    for (String aug : augmentedUtterances)
                        print(aug);
                }
            }

            // Write all the utterances if the whole xml file is a document.
            if (!utterancePerDoc)
                print(fileBuilder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
1003134
public void addTerm(OntologyTerm term) {
        terms.put(term.getId(), term);
        indexTerm(term);
        isTypeOfIsBuilt = false;
    }