| Total Complexity | 61 |
| Total Lines | 214 |
| Duplicated Lines | 0 % |
Complex classes like goatools.OBOReader often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
| 1 | # Copyright 2010-2016 by Haibao Tang et al. All rights reserved. |
||
| 20 | class OBOReader(object): |
||
| 21 | """Read goatools.org's obo file. Load into this iterable class. |
||
| 22 | |||
| 23 | Download obo from: http://geneontology.org/ontology/go-basic.obo |
||
| 24 | |||
| 25 | >>> reader = OBOReader() |
||
| 26 | >>> for rec in reader: |
||
| 27 | print rec |
||
| 28 | """ |
||
| 29 | |||
| 30 | def __init__(self, obo_file="go-basic.obo", optional_attrs=None): |
||
| 31 | """Read obo file. Load dictionary.""" |
||
| 32 | self._init_optional_attrs(optional_attrs) |
||
| 33 | self.format_version = None |
||
| 34 | self.data_version = None |
||
| 35 | self.typedefs = {} |
||
| 36 | |||
| 37 | # True if obo file exists or if a link to an obo file exists. |
||
| 38 | if os.path.isfile(obo_file): |
||
| 39 | self.obo_file = obo_file |
||
| 40 | # GOTerm attributes that are necessary for any operations: |
||
| 41 | else: |
||
| 42 | raise Exception("download obo file first\n " |
||
| 43 | "[http://geneontology.org/ontology/" |
||
| 44 | "go-basic.obo]") |
||
| 45 | |||
| 46 | def __iter__(self): |
||
| 47 | """Return one GO Term record at a time from an obo file.""" |
||
| 48 | # Written by DV Klopfenstein |
||
| 49 | # Wait to open file until needed. Automatically close file when done. |
||
| 50 | with open(self.obo_file) as fstream: |
||
| 51 | rec_curr = None # Stores current GO Term |
||
| 52 | typedef_curr = None # Stores current typedef |
||
| 53 | for lnum, line in enumerate(fstream): |
||
| 54 | # obo lines start with any of: [Term], [Typedef], /^\S+:/, or /^\s*/ |
||
| 55 | if self.data_version is None: |
||
| 56 | self._init_obo_version(line) |
||
| 57 | if line[0:6].lower() == "[term]": |
||
| 58 | rec_curr = self._init_goterm_ref(rec_curr, "Term", lnum) |
||
| 59 | elif line[0:9].lower() == "[typedef]": |
||
| 60 | typedef_curr = self._init_typedef(rec_curr, "Typedef", lnum) |
||
| 61 | elif rec_curr is not None or typedef_curr is not None: |
||
| 62 | line = line.rstrip() # chomp |
||
| 63 | if ":" in line: |
||
| 64 | if rec_curr is not None: |
||
| 65 | self._add_to_ref(rec_curr, line, lnum) |
||
| 66 | else: |
||
| 67 | self._add_to_typedef(typedef_curr, line, lnum) |
||
| 68 | elif line == "": |
||
| 69 | if rec_curr is not None: |
||
| 70 | yield rec_curr |
||
| 71 | rec_curr = None |
||
| 72 | elif typedef_curr is not None: |
||
| 73 | # Save typedef. |
||
| 74 | self.typedefs[typedef_curr.id] = typedef_curr |
||
| 75 | typedef_curr = None |
||
| 76 | else: |
||
| 77 | self._die("UNEXPECTED LINE CONTENT: {L}".format(L=line), lnum) |
||
| 78 | # Return last record, if necessary |
||
| 79 | if rec_curr is not None: |
||
| 80 | yield rec_curr |
||
| 81 | |||
| 82 | def _init_obo_version(self, line): |
||
| 83 | """Save obo version and release.""" |
||
| 84 | if line[0:14] == "format-version": |
||
| 85 | self.format_version = line[16:-1] |
||
| 86 | if line[0:12] == "data-version": |
||
| 87 | self.data_version = line[14:-1] |
||
| 88 | |||
| 89 | def _init_goterm_ref(self, rec_curr, name, lnum): |
||
| 90 | """Initialize new reference and perform checks.""" |
||
| 91 | if rec_curr is None: |
||
| 92 | return GOTerm() |
||
| 93 | msg = "PREVIOUS {REC} WAS NOT TERMINATED AS EXPECTED".format(REC=name) |
||
| 94 | self._die(msg, lnum) |
||
| 95 | |||
| 96 | def _init_typedef(self, typedef_curr, name, lnum): |
||
| 97 | """Initialize new typedef and perform checks.""" |
||
| 98 | if typedef_curr is None: |
||
| 99 | return TypeDef() |
||
| 100 | msg = "PREVIOUS {REC} WAS NOT TERMINATED AS EXPECTED".format(REC=name) |
||
| 101 | self._die(msg, lnum) |
||
| 102 | |||
| 103 | def _add_to_ref(self, rec_curr, line, lnum): |
||
| 104 | """Add new fields to the current reference.""" |
||
| 105 | # Written by DV Klopfenstein |
||
| 106 | # Examples of record lines containing ':' include: |
||
| 107 | # id: GO:0000002 |
||
| 108 | # name: mitochondrial genome maintenance |
||
| 109 | # namespace: biological_process |
||
| 110 | # def: "The maintenance of ... |
||
| 111 | # is_a: GO:0007005 ! mitochondrion organization |
||
| 112 | mtch = re.match(r'^(\S+):\s*(\S.*)$', line) |
||
| 113 | if mtch: |
||
| 114 | field_name = mtch.group(1) |
||
| 115 | field_value = mtch.group(2) |
||
| 116 | if field_name == "id": |
||
| 117 | self._chk_none(rec_curr.id, lnum) |
||
| 118 | rec_curr.id = field_value |
||
| 119 | elif field_name == "alt_id": |
||
| 120 | rec_curr.alt_ids.append(field_value) |
||
| 121 | elif field_name == "name": |
||
| 122 | self._chk_none(rec_curr.name, lnum) |
||
| 123 | rec_curr.name = field_value |
||
| 124 | elif field_name == "namespace": |
||
| 125 | self._chk_none(rec_curr.namespace, lnum) |
||
| 126 | rec_curr.namespace = field_value |
||
| 127 | elif field_name == "is_a": |
||
| 128 | rec_curr._parents.append(field_value.split()[0]) |
||
| 129 | elif field_name == "is_obsolete" and field_value == "true": |
||
| 130 | rec_curr.is_obsolete = True |
||
| 131 | elif field_name in self.optional_attrs: |
||
| 132 | self.update_rec(rec_curr, field_name, field_value) |
||
| 133 | else: |
||
| 134 | self._die("UNEXPECTED FIELD CONTENT: {L}\n".format(L=line), lnum) |
||
| 135 | |||
| 136 | def update_rec(self, rec, name, value): |
||
| 137 | """Update current GOTerm with optional record.""" |
||
| 138 | # 'def' is a reserved word in python, do not use it as a Class attr. |
||
| 139 | if name == "def": |
||
| 140 | name = "defn" |
||
| 141 | |||
| 142 | # If we have a relationship, then we will split this into a further |
||
| 143 | # dictionary. |
||
| 144 | |||
| 145 | if hasattr(rec, name): |
||
| 146 | if name not in self.attrs_scalar: |
||
| 147 | if name not in self.attrs_nested: |
||
| 148 | getattr(rec, name).add(value) |
||
| 149 | else: |
||
| 150 | self._add_nested(rec, name, value) |
||
| 151 | else: |
||
| 152 | raise Exception("ATTR({NAME}) ALREADY SET({VAL})".format( |
||
| 153 | NAME=name, VAL=getattr(rec, name))) |
||
| 154 | else: # Initialize new GOTerm attr |
||
| 155 | if name in self.attrs_scalar: |
||
| 156 | setattr(rec, name, value) |
||
| 157 | elif name not in self.attrs_nested: |
||
| 158 | setattr(rec, name, set([value])) |
||
| 159 | else: |
||
| 160 | name = '_{:s}'.format(name) |
||
| 161 | setattr(rec, name, defaultdict(list)) |
||
| 162 | self._add_nested(rec, name, value) |
||
| 163 | |||
| 164 | def _add_to_typedef(self, typedef_curr, line, lnum): |
||
| 165 | """Add new fields to the current typedef.""" |
||
| 166 | mtch = re.match(r'^(\S+):\s*(\S.*)$', line) |
||
| 167 | if mtch: |
||
| 168 | field_name = mtch.group(1) |
||
| 169 | field_value = mtch.group(2).split('!')[0].rstrip() |
||
| 170 | |||
| 171 | if field_name == "id": |
||
| 172 | self._chk_none(typedef_curr.id, lnum) |
||
| 173 | typedef_curr.id = field_value |
||
| 174 | elif field_name == "name": |
||
| 175 | self._chk_none(typedef_curr.name, lnum) |
||
| 176 | typedef_curr.name = field_value |
||
| 177 | elif field_name == "transitive_over": |
||
| 178 | typedef_curr.transitive_over.append(field_value) |
||
| 179 | elif field_name == "inverse_of": |
||
| 180 | self._chk_none(typedef_curr.inverse_of, lnum) |
||
| 181 | typedef_curr.inverse_of = field_value |
||
| 182 | # Note: there are other tags that aren't imported here. |
||
| 183 | else: |
||
| 184 | self._die("UNEXPECTED FIELD CONTENT: {L}\n".format(L=line), lnum) |
||
| 185 | |||
| 186 | def _add_nested(self, rec, name, value): |
||
| 187 | """Adds a term's nested attributes.""" |
||
| 188 | # Remove comments and split term into typedef / target term. |
||
| 189 | (typedef, target_term) = value.split('!')[0].rstrip().split(' ') |
||
| 190 | |||
| 191 | # Save the nested term. |
||
| 192 | getattr(rec, name)[typedef].append(target_term) |
||
| 193 | |||
| 194 | def _init_optional_attrs(self, optional_attrs): |
||
| 195 | """Prepare to store data from user-desired optional fields. |
||
| 196 | |||
| 197 | Not loading these optional fields by default saves in space and speed. |
||
| 198 | But allow the possibility for saving these fields, if the user desires, |
||
| 199 | Including: |
||
| 200 | comment consider def is_class_level is_metadata_tag is_transitive |
||
| 201 | relationship replaced_by subset synonym transitive_over xref |
||
| 202 | """ |
||
| 203 | # Written by DV Klopfenstein |
||
| 204 | # Required attributes are always loaded. All others are optionally loaded. |
||
| 205 | self.attrs_req = ['id', 'alt_id', 'name', 'namespace', 'is_a', 'is_obsolete'] |
||
| 206 | self.attrs_scalar = ['comment', 'defn', |
||
| 207 | 'is_class_level', 'is_metadata_tag', |
||
| 208 | 'is_transitive', 'transitive_over'] |
||
| 209 | self.attrs_nested = frozenset(['relationship']) |
||
| 210 | # Allow user to specify either: 'def' or 'defn' |
||
| 211 | # 'def' is an obo field name, but 'defn' is legal Python attribute name |
||
| 212 | fnc = lambda aopt: aopt if aopt != "defn" else "def" |
||
| 213 | if optional_attrs is None: |
||
| 214 | optional_attrs = [] |
||
| 215 | elif isinstance(optional_attrs, str): |
||
| 216 | optional_attrs = [fnc(optional_attrs)] if optional_attrs not in self.attrs_req else [] |
||
| 217 | elif isinstance(optional_attrs, list) or isinstance(optional_attrs, set): |
||
| 218 | optional_attrs = set([fnc(f) for f in optional_attrs if f not in self.attrs_req]) |
||
| 219 | else: |
||
| 220 | raise Exception("optional_attrs arg MUST BE A str, list, or set.") |
||
| 221 | self.optional_attrs = optional_attrs |
||
| 222 | |||
| 223 | |||
| 224 | def _die(self, msg, lnum): |
||
| 225 | """Raise an Exception if file read is unexpected.""" |
||
| 226 | raise Exception("**FATAL {FILE}({LNUM}): {MSG}\n".format( |
||
| 227 | FILE=self.obo_file, LNUM=lnum, MSG=msg)) |
||
| 228 | |||
| 229 | def _chk_none(self, init_val, lnum): |
||
| 230 | """Expect these lines to be uninitialized.""" |
||
| 231 | if init_val is None or init_val is "": |
||
| 232 | return |
||
| 233 | self._die("FIELD IS ALREADY INITIALIZED", lnum) |
||
| 234 | |||
| 663 |