GFF3Importer.inc 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960
  1. <?php
  2. class GFF3Importer extends TripalImporter {
  3. /**
  4. * The name of this loader. This name will be presented to the site
  5. * user.
  6. */
  7. public static $name = 'Chado GFF3 File Loader';
  8. /**
  9. * The machine name for this loader. This name will be used to construct
  10. * the URL for the loader.
  11. */
  12. public static $machine_name = 'chado_gff3_loader';
  13. /**
  14. * A brief description for this loader. This description will be
  15. * presented to the site user.
  16. */
  17. public static $description = 'Import a GFF3 file into Chado';
  18. /**
  19. * An array containing the extensions of allowed file types.
  20. */
  21. public static $file_types = ['gff', 'gff3'];
  22. /**
  23. * Provides information to the user about the file upload. Typically this
  24. * may include a description of the file types allowed.
  25. */
  26. public static $upload_description = 'Please provide the GFF3 file.';
  27. /**
  28. * The title that should appear above the upload button.
  29. */
  30. public static $upload_title = 'GFF3 File';
  31. /**
  32. * Text that should appear on the button at the bottom of the importer
  33. * form.
  34. */
  35. public static $button_text = 'Import GFF3 file';
  36. /**
  37. * A handle to a temporary file for caching the GFF features. This allows for
  38. * quick lookup of parsed features without having to store it in RAM.
  39. */
  40. private $gff_cache_file = NULL;
  41. /**
  42. * The name of the temporary cache file.
  43. */
  44. private $gff_cache_file_name = NULL;
  45. /**
  46. * The lines from the ##sequence-region at the top of the GFF
  47. */
  48. private $seq_region_headers = [];
  49. /**
  50. * The path to the GFF3 file.
  51. */
  52. private $gff_file = NULL;
  53. /**
  54. * The file handle for the GFF3 file.
  55. */
  56. private $gff_file_h = NULL;
  57. /**
  58. * The organism ID for this GFF file.
  59. */
  60. private $organism_id = NULL;
  61. /**
  62. * The organism ChadoRecord object that corresponds to the $organism_id value.
  63. */
  64. private $organism = NULL;
  65. /**
  66. * An array of organism records for quick lookup.
  67. */
  68. private $organism_lookup = [];
  69. /**
  70. * The analysis ID for this GFF file
  71. */
  72. private $analysis_id = NULL;
  73. /**
  74. * The analysis ChadoRecord object that corresponds to the $analysis_id value.
  75. */
  76. private $analysis = NULL;
  77. /**
  78. * A flag indicating if only new items should be added (no updates)
  79. */
  80. private $add_only = NULL;
  81. /**
  82. * A flag indicting if only existing items should be updated.
  83. */
  84. private $update = TRUE;
  85. /**
  86. * If the GFF file contains a 'Target' attribute then the feature and the
  87. * target will have an alignment created, but to find the proper target
  88. * feature the target organism must also be known. If different from the
  89. * organism specified for the GFF file, then use this argument to specify
  90. * the target organism. Only use this argument if all target sequences
  91. * belong to the same species. If the targets in the GFF file belong to
  92. * multiple different species then the organism must be specified using the
  93. * 'target_organism=genus:species' attribute in the GFF file. Default is
  94. * NULL.
  95. */
  96. private $target_organism_id = NULL;
  97. /**
  98. * If the GFF file contains a 'Target' attribute then the feature and the
  99. * target will have an alignment created, but to find the proper target
  100. * feature the target organism must also be known. This can be used to
  101. * specify the target feature type to help with identification of the
  102. * target feature. Only use this argument if all target sequences types are
  103. * the same. If the targets are of different types then the type must be
  104. * specified using the 'target_type=type' attribute in the GFF file. This
  105. * must be a valid Sequence Ontology (SO) term. Default is NULL
  106. */
  107. private $target_type = NULL;
  108. private $target_type_id = NULL;
  109. /**
  110. * A flag indicating if the target feature should be created. If FALSE
  111. * then it should already exist.
  112. */
  113. private $create_target = FALSE;
  114. /**
  115. * Set this to the line in the GFF file where importing should start. This
  116. * is useful for testing and debugging GFF files that may have problems and
  117. * you want to start at a particular line to speed testing. Default = 1
  118. */
  119. private $start_line = 1;
  120. /**
  121. * During parsing of the GFF file this keeps track of the current line
  122. * number.
  123. */
  124. private $current_line = 0;
  125. /**
  126. * A Sequence Ontology term name for the landmark sequences in the GFF
  127. * file (e.g. 'chromosome'), if the GFF file contains a '##sequence-region'
  128. * line that describes the landmark sequences. Default = ''
  129. */
  130. private $landmark_type = '';
  131. /**
  132. * The ChadoRecord object for the landmark type cvterm.
  133. */
  134. private $landmark_cvterm = NULL;
  135. /**
  136. * Regular expression to pull out the mRNA name.
  137. */
  138. private $re_mrna = '';
  139. /**
  140. * Regular expression to pull out the protein name.
  141. */
  142. private $re_protein = '';
  143. /**
  144. * A flag that indicates if a protein record should be created.
  145. * @var integer
  146. */
  147. private $skip_protein = 0;
  148. /**
  149. * Sometimes lines in the GFF file are missing the required ID attribute
  150. * that specifies the unique name of the feature. If so, you may specify
  151. * the name of an existing attribute to use for the ID.
  152. */
  153. private $alt_id_attr = '';
  154. /**
  155. * The Tripal GFF loader supports the "organism" attribute. This allows
  156. * features of a different organism to be aligned to the landmark sequence
  157. * of another species. The format of the attribute is
  158. * "organism=[genus]:[species]", where [genus] is the organism's genus and
  159. * [species] is the species name. Check this box to automatically add the
  160. * organism to the database if it does not already exists. Otherwise lines
  161. * with an oraganism attribute where the organism is not present in the
  162. * database will be skipped.
  163. */
  164. private $create_organism = FALSE;
  165. /**
  166. * Holds mapping of DB names to DB ids.
  167. */
  168. private $db_lookup = [];
  169. /**
  170. * Holds a mapping of Dbxref names to ids.
  171. */
  172. private $dbxref_lookup = [];
  173. /**
  174. * Holds a mapping of Dbxref names to cvterm ids.
  175. */
  176. private $cvterm_lookup = [];
  177. /**
  178. * Holds a mapping of synonymns to ids.
  179. */
  180. private $synonym_lookup = [];
  181. /**
  182. * Maps parents to their children and contains the ranks of the children.
  183. */
  184. private $parent_lookup = [];
  185. /**
  186. * An array that stores CVterms that have been looked up so we don't have
  187. * to do the database query every time.
  188. */
  189. private $feature_cvterm_lookup = [];
  190. /**
  191. * An array that stores CVterms that have been looked up so we don't have
  192. * to do the database query every time.
  193. */
  194. private $featureprop_cvterm_lookup = [];
  195. /**
  196. * Holds the CV term for the "exact" synonym.
  197. */
  198. private $exact_syn = NULL;
  199. /**
  200. * Holds the object for the null publication record.
  201. */
  202. private $null_pub = NULL;
  203. /**
  204. * The list of features from the GFF3 file. Each element is an
  205. * associative array of the columns from the GFF3 file, with the attribute
  206. * field being an associative array of key/value pairs.
  207. */
  208. private $features = [];
  209. /**
  210. * An associatiave array containing the pointers to the FASTA sequences
  211. * in the GFF file. We don't want to load these into memory as they
  212. * may be too big!
  213. */
  214. private $residue_index = [];
  215. /**
  216. * An array that stores landmarks objects. Landmarks should be inserted
  217. * first if they don't already exist.
  218. */
  219. private $landmarks = [];
  220. /**
  221. * A controlled vocabulary ChadoRecord object. This is the CV that will be
  222. * used to for feature properties.
  223. */
  224. private $feature_prop_cv = NULL;
  225. /**
  226. * A controlled vocabulary ChadoRecord object. This is the CV that will be
  227. * used to for feature properties.
  228. */
  229. private $feature_cv = NULL;
  230. /**
  231. * Stores proteins
  232. */
  233. private $proteins = [];
  234. /**
  235. * @see TripalImporter::form()
  236. */
  237. public function form($form, &$form_state) {
  238. // get the list of organisms
  239. $sql = "SELECT * FROM {organism} ORDER BY genus, species";
  240. $org_rset = chado_query($sql);
  241. $organisms = [];
  242. $organisms[''] = '';
  243. while ($organism = $org_rset->fetchObject()) {
  244. $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
  245. }
  246. $form['organism_id'] = [
  247. '#title' => t('Existing Organism'),
  248. '#type' => 'select',
  249. '#description' => t("Choose an existing organism to which the entries in the GFF file will be associated."),
  250. '#required' => TRUE,
  251. '#options' => $organisms,
  252. ];
  253. $form['create_organism'] = [
  254. '#type' => 'checkbox',
  255. '#title' => t('Create organism'),
  256. '#required' => FALSE,
  257. '#description' => t('The Tripal GFF loader supports the "organism" attribute. This allows features of a
  258. different organism to be aligned to the landmark sequence. The format of the
  259. attribute is "organism=[genus]:[species]", where [genus] is the organism\'s genus and [species] is the
  260. species name. Check this box to automatically add the organism to the database if it does not already exists.
  261. Otherwise lines with an organism attribute where the organism is not present in the database will be skipped.'),
  262. ];
  263. $form['landmark_type'] = [
  264. '#title' => t('Landmark Type'),
  265. '#type' => 'textfield',
  266. '#description' => t("Optional. Use this field to specify a Sequence Ontology type
  267. for the landmark sequences in the GFF fie (e.g. 'chromosome'). This is only needed if
  268. the landmark features (first column of the GFF3 file) are not already in the database.."),
  269. ];
  270. $form['proteins'] = [
  271. '#type' => 'fieldset',
  272. '#title' => t('Proteins'),
  273. '#collapsible' => TRUE,
  274. '#collapsed' => FALSE,
  275. ];
  276. $form['proteins']['skip_protein'] = [
  277. '#type' => 'checkbox',
  278. '#title' => t('Skip automatic protein creation'),
  279. '#required' => FALSE,
  280. '#description' => t('The GFF loader will automatically create a protein feature for each transcript in the GFF file if a protein feature is missing in the GFF file. Check this box to disable this functionality. Protein features that are specifically present in the GFF will always be created.'),
  281. '#default_value' => 0,
  282. ];
  283. $form['proteins']['re_mrna'] = [
  284. '#type' => 'textfield',
  285. '#title' => t('Optional. Regular expression for the mRNA name'),
  286. '#required' => FALSE,
  287. '#description' => t('If automatic protein creation is enabled, then by default the loader will give each protein a name based on the name of the corresponding mRNA followed by the "-protein" suffix.
  288. If you want to customize the name of the created protein, you can enter a regular expression that will extract portions of
  289. the mRNA unique name. For example, for a
  290. mRNA with a unique name finishing by -RX (e.g. SPECIES0000001-RA),
  291. the regular expression would be, "^(.*?)-R([A-Z]+)$". Elements surrounded by parentheses are captured as backreferences and can be used for replacement.' ),
  292. ];
  293. $form['proteins']['re_protein'] = [
  294. '#type' => 'textfield',
  295. '#title' => t('Optional. Replacement string for the protein name'),
  296. '#required' => FALSE,
  297. '#description' => t('If a regular expression is used to specify a protein name you can use the backreference tokens to extract the portion of the mRNA name that you want to use for a protein.
  298. You use a dollar sign followed by a number to indicate the backreferences. For example: "$1-P$2".'),
  299. ];
  300. $form['targets'] = [
  301. '#type' => 'fieldset',
  302. '#title' => t('Targets'),
  303. '#collapsible' => TRUE,
  304. '#collapsed' => FALSE,
  305. ];
  306. $form['targets']['adesc'] = [
  307. '#markup' => t("When alignments are represented in the GFF file (e.g. such as
  308. alignments of cDNA sequences to a whole genome, or blast matches), they are
  309. represented using the term 'match' or more specific match types: 'cDNA_match', 'EST_match', etc.
  310. These features may also have a 'Target' attribute to
  311. specify the sequence that is being aligned and the alignment coordinates on that sequence.
  312. However, the organism to which the aligned sequence belongs may not be present in the
  313. GFF file. Here you can specify the organism and feature type of the target sequences.
  314. The options here will apply to all targets unless the organism and type are explicity
  315. set in the GFF file using the 'target_organism' and 'target_type' attributes, or for the
  316. type if a more specific type name is given (e.g. cDNA_match or EST_match)."),
  317. ];
  318. $form['targets']['target_organism_id'] = [
  319. '#title' => t('Target Organism'),
  320. '#type' => t('select'),
  321. '#description' => t("Optional. Choose the organism to which target sequences belong.
  322. Select this only if target sequences belong to a different organism than the
  323. one specified above. And only choose an organism here if all of the target sequences
  324. belong to the same species. If the targets in the GFF file belong to multiple
  325. different species then the organism must be specified using the 'target_organism=genus:species'
  326. attribute in the GFF file."),
  327. '#options' => $organisms,
  328. ];
  329. $form['targets']['target_type'] = [
  330. '#title' => t('Target Type'),
  331. '#type' => t('textfield'),
  332. '#description' => t("Optional. If the unique name for a target sequence is not unique (e.g. a protein
  333. and an mRNA have the same name) then you must specify the type for all targets in the GFF file. If
  334. the targets are of different types then the type must be specified using the 'target_type=type' attribute
  335. in the GFF file. This must be a valid Sequence Ontology (SO) term. If the matches in the GFF3 file
  336. use specific match types (e.g. cDNA_match, EST_match, etc.) then this can be left blank. "),
  337. ];
  338. $form['targets']['create_target'] = [
  339. '#type' => 'checkbox',
  340. '#title' => t('Create Target'),
  341. '#required' => FALSE,
  342. '#description' => t("If the target feature cannot be found, create one using the organism and type specified above, or
  343. using the 'target_organism' and 'target_type' fields specified in the GFF file. Values specified in the
  344. GFF file take precedence over those specified above."),
  345. ];
  346. // Advanced Options
  347. $form['advanced'] = [
  348. '#type' => 'fieldset',
  349. '#title' => t('Additional Options'),
  350. '#collapsible' => TRUE,
  351. '#collapsed' => FALSE,
  352. ];
  353. $form['advanced']['line_number'] = [
  354. '#type' => 'textfield',
  355. '#title' => t('Start Line Number'),
  356. '#description' => t('Enter the line number in the GFF file where you would like to begin processing. The
  357. first line is line number 1. This option is useful for examining loading problems with large GFF files.'),
  358. '#size' => 10,
  359. ];
  360. $form['advanced']['alt_id_attr'] = [
  361. '#title' => t('ID Attribute'),
  362. '#type' => t('textfield'),
  363. '#description' => t("Optional. Sometimes lines in the GFF file are missing the
  364. required ID attribute that specifies the unique name of the feature, but there
  365. may be another attribute that can uniquely identify the feature. If so,
  366. you may specify the name of the attribute to use for the name."),
  367. ];
  368. return $form;
  369. }
  370. /**
  371. * @see TripalImporter::formValidate()
  372. */
  373. public function formValidate($form, &$form_state) {
  374. $organism_id = $form_state['values']['organism_id'];
  375. $target_organism_id = $form_state['values']['target_organism_id'];
  376. $target_type = trim($form_state['values']['target_type']);
  377. $create_target = $form_state['values']['create_target'];
  378. $create_organism = $form_state['values']['create_organism'];
  379. $refresh = 0; //$form_state['values']['refresh'];
  380. $remove = 0; //$form_state['values']['remove'];
  381. $line_number = trim($form_state['values']['line_number']);
  382. $landmark_type = trim($form_state['values']['landmark_type']);
  383. $alt_id_attr = trim($form_state['values']['alt_id_attr']);
  384. $re_mrna = trim($form_state['values']['re_mrna']);
  385. $re_protein = trim($form_state['values']['re_protein']);
  386. if ($line_number and !is_numeric($line_number) or $line_number < 0) {
  387. form_set_error('line_number', t("Please provide an integer line number greater than zero."));
  388. }
  389. if (!($re_mrna and $re_protein) and ($re_mrna or $re_protein)) {
  390. form_set_error('re_uname', t("You must provide both a regular expression for mRNA and a replacement string for protein"));
  391. }
  392. // check the regular expression to make sure it is valid
  393. set_error_handler(function () {
  394. }, E_WARNING);
  395. $result_re = preg_match("/" . $re_mrna . "/", NULL);
  396. $result = preg_replace("/" . $re_mrna . "/", $re_protein, NULL);
  397. restore_error_handler();
  398. if ($result_re === FALSE) {
  399. form_set_error('re_mrna', 'Invalid regular expression.');
  400. }
  401. else {
  402. if ($result === FALSE) {
  403. form_set_error('re_protein', 'Invalid replacement string.');
  404. }
  405. }
  406. }
  407. /**
  408. * @see TripalImporter::run()
  409. */
  410. public function run() {
  411. $arguments = $this->arguments['run_args'];
  412. $this->gff_file = $this->arguments['files'][0]['file_path'];
  413. // Set the private member variables of this class using the loader inputs.
  414. $this->organism_id = $arguments['organism_id'];
  415. $this->analysis_id = $arguments['analysis_id'];
  416. $this->add_only = $arguments['add_only'];
  417. $this->update = $arguments['update'];
  418. $this->target_organism_id = $arguments['target_organism_id'];
  419. $this->target_type = $arguments['target_type'];
  420. $this->create_target = $arguments['create_target'];
  421. $this->start_line = $arguments['line_number'];
  422. $this->landmark_type = $arguments['landmark_type'];
  423. $this->alt_id_attr = $arguments['alt_id_attr'];
  424. $this->create_organism = $arguments['create_organism'];
  425. $this->re_mrna = $arguments['re_mrna'];
  426. $this->re_protein = $arguments['re_protein'];
  427. $this->skip_protein = $arguments['skip_protein'];
  428. // Check to see if the file is located local to Drupal
  429. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $this->gff_file;
  430. if (!file_exists($dfile)) {
  431. $this->gff_file = $dfile;
  432. }
  433. // If the file is not local to Drupal check if it exists on the system.
  434. else if (!file_exists($this->gff_file)) {
  435. throw new Exception(t("Cannot find the file: !file", ['!file' => $this->gff_file]));
  436. }
  437. // Open the GFF3 file.
  438. $this->logMessage("Opening !gff_file", ['!gff_file' => $this->gff_file]);
  439. $this->gff_file_h = fopen($this->gff_file, 'r');
  440. if (!$this->gff_file_h) {
  441. throw new Exception(t("Cannot open file: !file", ['!file' => $this->gff_file]));
  442. }
  443. // Get the feature property CV object
  444. $this->feature_prop_cv = new ChadoRecord('cv');
  445. $this->feature_prop_cv->setValues(['name' => 'feature_property']);
  446. $num_found = $this->feature_prop_cv->find();
  447. if ($num_found == 0) {
  448. throw new Exception(t("Cannot find the 'feature_property' ontology'", []));
  449. }
  450. // Get the sequence CV object.
  451. $this->feature_cv = new ChadoRecord('cv');
  452. $this->feature_cv->setValues(['name' => 'sequence']);
  453. $num_found = $this->feature_cv->find();
  454. if ($num_found == 0) {
  455. throw new Exception(t("Cannot find the 'sequence' ontology'", []));
  456. }
  457. // Get the organism object.
  458. $this->organism = new ChadoRecord('organism');
  459. $this->organism->setValues(['organism_id' => $this->organism_id]);
  460. $num_found = $this->organism->find();
  461. if ($num_found == 0) {
  462. throw new Exception(t("Cannot find the specified organism for this GFF3 file."));
  463. }
  464. // Get the analysis object.
  465. $this->analysis = new ChadoRecord('analysis');
  466. $this->analysis->setValues(['analysis_id' => $this->analysis_id]);
  467. $num_found = $this->analysis->find();
  468. if ($num_found == 0) {
  469. throw new Exception(t("Cannot find the specified organism for this GFF3 file."));
  470. }
  471. // If a landmark type was provided then get that object.
  472. if ($this->landmark_type) {
  473. $this->landmark_cvterm = new ChadoRecord('cvterm');
  474. $this->landmark_cvterm->setValues([
  475. 'cv_id' => $this->feature_cv->getValue('cv_id'),
  476. 'name' => $this->landmark_type,
  477. ]);
  478. $num_found = $this->landmark_cvterm->find();
  479. if ($num_found == 0) {
  480. throw new Exception(t('Cannot find landmark feature type \'%landmark_type\'.', ['%landmark_type' => $this->landmark_type]));
  481. }
  482. }
  483. // If a target type is provided then get the ID.
  484. if ($this->target_type) {
  485. $target_type = new ChadoRecord('cvterm');
  486. $target_type->setValues([
  487. 'name' => $this->target_type,
  488. 'cv_id' => $this->feature_cv->getID()
  489. ]);
  490. $num_found = $target_type->find();
  491. if ($num_found == 0) {
  492. throw new Exception(t("Cannot find the specified target type, !type.", ['!type' => $this->target_type]));
  493. }
  494. $this->target_type_id = $target_type->getID();
  495. }
  496. // Create the cache file for storing parsed GFF entries.
  497. $this->openCacheFile();
  498. // Load the GFF3.
  499. try {
  500. $this->logMessage("Step 1 of 26: Caching GFF3 file... ");
  501. $this->parseGFF3();
  502. // Prep the database for necessary records.
  503. $this->prepSynonms();
  504. $this->prepNullPub();
  505. $this->prepDBs();
  506. $this->logMessage("Step 2 of 26: Find existing landmarks... ");
  507. $this->findLandmarks();
  508. $this->logMessage("Step 3 of 26: Insert new landmarks (if needed)... ");
  509. $this->insertLandmarks();
  510. if (!$this->skip_protein) {
  511. $this->logMessage("Step 4 of 26: Find missing proteins... ");
  512. $this->findMissingProteins();
  513. $this->logMessage("Step 5 of 26: Add missing proteins to list of features... ");
  514. $this->addMissingProteins();
  515. }
  516. else {
  517. $this->logMessage("Step 4 of 26: Find missing proteins (Skipped)... ");
  518. $this->logMessage("Step 5 of 26: Add missing proteins to list of features (Skipped)...");
  519. }
  520. $this->logMessage("Step 6 of 26: Find existing features... ");
  521. $this->findFeatures();
  522. $this->logMessage("Step 7 of 26: Clear attributes of existing features... ");
  523. $this->deleteFeatureData();
  524. $this->logMessage("Step 8 of 26: Processing !num_features features... ",
  525. ['!num_features' => number_format(count(array_keys($this->features)))]);
  526. $this->insertFeatures();
  527. $this->logMessage("Step 9 of 26: Get new feature IDs... ");
  528. $this->findFeatures();
  529. $this->logMessage("Step 10 of 26: Insert locations... ");
  530. $this->insertFeatureLocs();
  531. $this->logMessage("Step 11 of 26: Associate parents and children... ");
  532. $this->associateChildren();
  533. $this->logMessage("Step 12 of 26: Calculate child ranks... ");
  534. $this->calculateChildRanks();
  535. $this->logMessage("Step 13 of 26: Add child-parent relationships... ");
  536. $this->insertFeatureParents();
  537. $this->logMessage("Step 14 of 26: Insert properties... ");
  538. $this->insertFeatureProps();
  539. $this->logMessage("Step 15 of 26: Find synonyms (aliases)... ");
  540. $this->findSynonyms();
  541. $this->logMessage("Step 16 of 26: Insert new synonyms (aliases)... ");
  542. $this->insertSynonyms();
  543. $this->logMessage("Step 17 of 26: Insert feature synonyms (aliases)... ");
  544. $this->insertFeatureSynonyms();
  545. $this->logMessage("Step 18 of 26: Find cross references... ");
  546. $this->findDbxrefs();
  547. $this->logMessage("Step 19 of 26: Insert new cross references... ");
  548. $this->insertDbxrefs();
  549. $this->logMessage("Step 20 of 26: Get new cross references IDs... ");
  550. $this->findDbxrefs();
  551. $this->logMessage("Step 21 of 26: Insert feature cross references... ");
  552. $this->insertFeatureDbxrefs();
  553. $this->logMessage("Step 22 of 26: Insert feature ontology terms... ");
  554. $this->insertFeatureCVterms();
  555. $this->logMessage("Step 23 of 26: Insert 'derives_from' relationships... ");
  556. $this->insertFeatureDerivesFrom();
  557. $this->logMessage("Step 24 of 26: Insert Targets... ");
  558. $this->insertFeatureTargets();
  559. $this->logMessage("Step 25 of 26: Associate features with analysis.... ");
  560. $this->insertFeatureAnalysis();
  561. if (!empty($this->residue_index)) {
  562. $this->logMessage("Step 26 of 26: Adding sequences data... ");
  563. $this->insertFeatureSeqs();
  564. }
  565. $this->logMessage("Step 26 of 26: Adding sequences data (Skipped: none available)...");
  566. }
  567. // On exception, catch the error, clean up the cache file and rethrow
  568. catch (Exception $e) {
  569. $this->closeCacheFile();
  570. throw $e;
  571. }
  572. }
  573. /**
  574. * Load a controlled vocabulary term.
  575. *
  576. * This method first checks if the term has already been loaded in the
  577. * feature_cvterm_lookup array, which helps a lot with performance.
  578. *
  579. * @param $type
  580. * @param $cv_id
  581. *
  582. * @ingroup gff3_loader
  583. */
  584. private function getTypeID($type, $is_prop_type) {
  585. $cv = $this->feature_cv;
  586. if ($is_prop_type) {
  587. $cv = $this->feature_prop_cv;
  588. }
  589. if ($is_prop_type) {
  590. if(array_key_exists(strtolower($type), $this->featureprop_cvterm_lookup)) {
  591. return $this->featureprop_cvterm_lookup[strtolower($type)];
  592. }
  593. }
  594. elseif (array_key_exists(strtolower($type), $this->feature_cvterm_lookup)) {
  595. return $this->feature_cvterm_lookup[strtolower($type)];
  596. }
  597. $sel_cvterm_sql = "
  598. SELECT CVT.cvterm_id
  599. FROM {cvterm} CVT
  600. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  601. WHERE CVT.cv_id = :cv_id and
  602. (lower(CVT.name) = lower(:name) or lower(CVTS.synonym) = lower(:synonym))
  603. ";
  604. $result = chado_query($sel_cvterm_sql, [
  605. ':cv_id' => $cv->getValue('cv_id'),
  606. ':name' => $type,
  607. ':synonym' => $type,
  608. ]);
  609. $cvterm_id = $result->fetchField();
  610. // If the term couldn't be found and it's a property term then insert it
  611. // as a local term.
  612. if (!$cvterm_id) {
  613. $term = [
  614. 'id' => "local:$type",
  615. 'name' => $type,
  616. 'is_obsolete' => 0,
  617. 'cv_name' => $cv->getValue('name'),
  618. 'db_name' => 'local',
  619. 'is_relationship' => FALSE,
  620. ];
  621. $cvterm = (object) chado_insert_cvterm($term, ['update_existing' => FALSE]);
  622. $cvterm_id = $cvterm->cvterm_id;
  623. }
  624. if ($is_prop_type) {
  625. $this->featureprop_cvterm_lookup[strtolower($cvterm->name)] = $cvterm_id;
  626. $this->featureprop_cvterm_lookup[strtolower($type)] = $cvterm_id;
  627. }
  628. else {
  629. $this->feature_cvterm_lookup[strtolower($cvterm->name)] = $cvterm_id;
  630. $this->feature_cvterm_lookup[strtolower($type)] = $cvterm_id;
  631. }
  632. return $cvterm_id;
  633. }
  634. /**
  635. * Makes sure Chado is ready with the necessary synonym type records.
  636. */
  637. private function prepSynonms() {
  638. // make sure we have a 'synonym_type' vocabulary
  639. $select = ['name' => 'synonym_type'];
  640. $results = chado_select_record('cv', ['*'], $select);
  641. if (count($results) == 0) {
  642. // insert the 'synonym_type' vocabulary
  643. $values = [
  644. 'name' => 'synonym_type',
  645. 'definition' => 'vocabulary for synonym types',
  646. ];
  647. $success = chado_insert_record('cv', $values, array(
  648. 'skip_validation' => TRUE,
  649. ));
  650. if (!$success) {
  651. $this->logMessage("Failed to add the synonyms type vocabulary.", [], TRIPAL_WARNING);
  652. return 0;
  653. }
  654. // now that we've added the cv we need to get the record
  655. $results = chado_select_record('cv', ['*'], $select);
  656. if (count($results) > 0) {
  657. $syncv = $results[0];
  658. }
  659. }
  660. else {
  661. $syncv = $results[0];
  662. }
  663. // get the 'exact' cvterm, which is the type of synonym we're adding
  664. $select = [
  665. 'name' => 'exact',
  666. 'cv_id' => [
  667. 'name' => 'synonym_type',
  668. ],
  669. ];
  670. $result = chado_select_record('cvterm', ['*'], $select);
  671. if (count($result) == 0) {
  672. $term = [
  673. 'name' => 'exact',
  674. 'id' => "synonym_type:exact",
  675. 'definition' => '',
  676. 'is_obsolete' => 0,
  677. 'cv_name' => $syncv->name,
  678. 'is_relationship' => FALSE,
  679. ];
  680. $syntype = chado_insert_cvterm($term, ['update_existing' => TRUE]);
  681. if (!$syntype) {
  682. $this->logMessage("Cannot add synonym type: internal:$type.", [], TRIPAL_WARNING);
  683. return 0;
  684. }
  685. }
  686. else {
  687. $syntype = $result[0];
  688. }
  689. $this->exact_syn = $syntype;
  690. }
  691. /**
  692. * Makes sure there is a null publication in the database.
  693. */
  694. private function prepNullPub(){
  695. // Check to see if we have a NULL publication in the pub table. If not,
  696. // then add one.
  697. $select = ['uniquename' => 'null'];
  698. $result = chado_select_record('pub', ['*'], $select);
  699. if (count($result) == 0) {
  700. $pub_sql = "
  701. INSERT INTO {pub} (uniquename,type_id)
  702. VALUES (:uname,
  703. (SELECT cvterm_id
  704. FROM {cvterm} CVT
  705. INNER JOIN {dbxref} DBX ON DBX.dbxref_id = CVT.dbxref_id
  706. INNER JOIN {db} DB ON DB.db_id = DBX.db_id
  707. WHERE CVT.name = :type_id))
  708. ";
  709. $status = chado_query($psql);
  710. if (!$status) {
  711. $this->logMessage("Cannot prepare statement 'ins_pub_uniquename_typeid.", [], TRIPAL_WARNING);
  712. return 0;
  713. }
  714. // Insert the null pub.
  715. $result = chado_query($pub_sql, [
  716. ':uname' => 'null',
  717. ':type_id' => 'null',
  718. ])->fetchObject();
  719. if (!$result) {
  720. $this->logMessage("Cannot add null publication needed for setup of alias.", [], TRIPAL_WARNING);
  721. return 0;
  722. }
  723. $result = chado_select_record('pub', ['*'], $select);
  724. $pub = $result[0];
  725. }
  726. else {
  727. $pub = $result[0];
  728. }
  729. $this->null_pub = $pub;
  730. }
  731. /**
  732. * Makes sure Chado is ready with the necessary DB records.
  733. */
  734. private function prepDBs() {
  735. // Get the list of database records that are needed by this GFF file. If
  736. // they do not exist then add them.
  737. $sql = "
  738. SELECT db_id
  739. FROM {db}
  740. WHERE name = :dbname";
  741. foreach (array_keys($this->db_lookup) as $dbname) {
  742. // First look for the database name if it doesn't exist then create one.
  743. // first check for the fully qualified URI (e.g. DB:<dbname>. If that
  744. // can't be found then look for the name as is. If it still can't be found
  745. // the create the database
  746. $values = ['name' => "DB:$dbname"];
  747. $db = chado_select_record('db', ['db_id'], $values);
  748. if (count($db) == 0) {
  749. $values = ['name' => "$dbname"];
  750. $db = chado_select_record('db', ['db_id'], $values);
  751. }
  752. if (count($db) == 0) {
  753. $values = [
  754. 'name' => $dbname,
  755. 'description' => 'Added automatically by the Triapl GFF loader.',
  756. ];
  757. $success = chado_insert_record('db', $values, array(
  758. 'skip_validation' => TRUE,
  759. ));
  760. if ($success) {
  761. $values = ['name' => "$dbname"];
  762. $db = chado_select_record('db', ['db_id'], $values);
  763. }
  764. else {
  765. $this->logMessage("Cannot find or add the database $dbname.", [], TRIPAL_WARNING);
  766. return 0;
  767. }
  768. }
  769. $this->db_lookup[$dbname] = $db[0]->db_id;
  770. }
  771. }
  772. /**
  773. * Parses the current line of the GFF3 file for a feature.
  774. *
  775. * @return array
  776. * An associative array containing the 9 elements othe GFF3 file. The
  777. * 9th element is an associative array of the attributes.
  778. */
  779. private function parseGFF3Line($line) {
  780. $date = getdate();
  781. // get the columns
  782. $cols = explode("\t", $line);
  783. if (sizeof($cols) != 9) {
  784. throw new Exception(t('Improper number of columns on line %line_num: %line', ['%line_num' => $this->current_line, '%line' => $line]));
  785. }
  786. $ret = [
  787. 'line' => $this->current_line,
  788. 'landmark' => $cols[0],
  789. 'source' => $cols[1],
  790. 'type' => strtolower($cols[2]),
  791. 'start' => $cols[3],
  792. 'stop' => $cols[4],
  793. 'score' => $cols[5],
  794. 'strand' => $cols[6],
  795. 'phase' => $cols[7],
  796. 'attrs' => [],
  797. ];
  798. // Ready the start and stop for chado. Chado expects these positions
  799. // to be zero-based, so we substract 1 from the fmin. Also, in case
  800. // they are backwards, put them in the right order.
  801. $fmin = $ret['start'] - 1;
  802. $fmax = $ret['stop'];
  803. if ($ret['stop'] < $ret['start']) {
  804. $fmin = $ret['stop'] - 1;
  805. $fmax = $ret['start'];
  806. }
  807. $ret['start'] = $fmin;
  808. $ret['stop'] = $fmax;
  809. // Landmark (seqid) validation checks based on GFF3 specifications
  810. preg_match('/[a-zA-Z0-9\.:\^\*\$@!\+_\?-\|]*/', $ret['landmark'], $matches);
  811. if ($matches[0] != $ret['landmark']) {
  812. throw new Exception(t("Landmark/seqid !landmark contains invalid
  813. characters. Only characters included in this regular expression is
  814. allowed [a-zA-Z0-9.:^*$@!+_?-|]",
  815. ['!landmark' => $ret['landmark']]));
  816. }
  817. // Check to make sure strand has a valid character
  818. if (preg_match('/[\+-\?\.]/',$ret['strand']) == false) {
  819. throw new Exception(t('Invalid strand detected on line !line,
  820. strand can only be +-?.',['!line' => $line]));
  821. }
  822. // Format the strand for chado
  823. if (strcmp($ret['strand'], '.') == 0) {
  824. $ret['strand'] = 0;
  825. }
  826. elseif (strcmp($ret['strand'], '?') == 0) {
  827. $ret['strand'] = 0;
  828. }
  829. elseif (strcmp($ret['strand'], '+') == 0) {
  830. $ret['strand'] = 1;
  831. }
  832. elseif (strcmp($ret['strand'], '-') == 0) {
  833. $ret['strand'] = -1;
  834. }
  835. if (preg_match('/[012\.]/',$ret['phase']) == false) {
  836. throw new Exception(t('Invalid phase detected on line !line,
  837. phase can only be 0,1,2 or . (period)',['!line' => $line]));
  838. }
  839. if (strcmp($ret['phase'], '.') == 0) {
  840. if ($ret['type'] == 'cds') {
  841. $ret['phase'] = '0';
  842. }
  843. else {
  844. $ret['phase'] = '';
  845. }
  846. }
  847. $tags = [];
  848. $attr_name = '';
  849. $attr_uniquename = '';
  850. $attrs = explode(";", $cols[8]);
  851. $attr_organism = $this->organism_id;
  852. $attr_parent = '';
  853. $attr_others = [];
  854. $attr_aliases = [];
  855. $attr_dbxref = [];
  856. $attr_derives = [];
  857. $attr_terms = [];
  858. $attr_target = [];
  859. foreach ($attrs as $attr) {
  860. $attr = rtrim($attr);
  861. $attr = ltrim($attr);
  862. if (strcmp($attr, '') == 0) {
  863. continue;
  864. }
  865. if (!preg_match('/^[^\=]+\=.+$/', $attr)) {
  866. throw new Exception(t('Attribute is not correctly formatted on line !line_num: !attr',
  867. ['!line_num' => $this->current_line, '!attr' => $attr]));
  868. }
  869. // Break apart each attribute into key/value pairs.
  870. $tag = preg_split("/=/", $attr, 2);
  871. // Multiple values of an attribute are separated by commas
  872. $tag_name = $tag[0];
  873. if (!array_key_exists($tag_name, $tags)) {
  874. $tags[$tag_name] = [];
  875. }
  876. $tags[$tag_name] = array_merge($tags[$tag_name], explode(",", $tag[1]));
  877. // Replace the URL escape codes for each tag
  878. for ($i = 0; $i < count($tags[$tag_name]); $i++) {
  879. $tags[$tag_name][$i] = urldecode($tags[$tag_name][$i]);
  880. }
  881. if (strcmp($tag_name, 'Alias') == 0) {
  882. $attr_aliases = array_merge($attr_aliases, $tags[$tag_name]);
  883. }
  884. elseif (strcmp($tag_name, 'Parent') == 0) {
  885. $attr_parent = $tag[1];
  886. }
  887. elseif (strcmp($tag_name, 'Dbxref') == 0) {
  888. $attr_dbxref = array_merge($attr_dbxref, $tags[$tag_name]);
  889. }
  890. elseif (strcmp($tag_name, 'Derives_from') == 0) {
  891. $attr_derives = array_merge($attr_derives, $tags[$tag_name]);
  892. }
  893. elseif (strcmp($tag_name, 'Ontology_term') == 0) {
  894. $attr_terms = array_merge($attr_terms, $tags[$tag_name]);
  895. }
  896. elseif (strcmp($tag_name, 'organism') == 0) {
  897. if (count($tags[$tag_name]) > 1) {
  898. throw new Exception(t('Each feature can only have one "organism" attribute. The feature %uniquename has more than one: %organism',
  899. ['%uniquename' => $ret['uniquename'], '%organism' => $ret['organism']]));
  900. }
  901. $attr_organism = $this->findOrganism($tags[$tag_name][0], $this->current_line);
  902. }
  903. elseif (strcmp($tag_name, 'Target') == 0) {
  904. if (count($tags[$tag_name]) > 1) {
  905. throw new Exception(t('Each feature can only have one "Target" attribute. The feature %uniquename has more than one.',
  906. ['%uniquename' => $ret['uniquename']]));
  907. }
  908. # Get the elements of the target.
  909. $matches = [];
  910. if (preg_match('/^(.*?)\s+(\d+)\s+(\d+)(\s+[\+|\-])*$/', trim($tags[$tag_name][0]), $matches)) {
  911. $attr_target['name'] = $matches[1];
  912. $attr_target['start'] = $matches[2];
  913. $attr_target['stop'] = $matches[3];
  914. $tfmin = $attr_target['start'] - 1;
  915. $tfmax = $attr_target['stop'];
  916. if ($attr_target['stop'] < $attr_target['start']) {
  917. $tfmin = $attr_target['stop'] - 1;
  918. $tfmax = $attr_target['start'];
  919. }
  920. $attr_target['start'] = $tfmin;
  921. $attr_target['stop'] = $tfmax;
  922. $attr_target['phase'] = '';
  923. $attr_target['strand'] = 0;
  924. if (!empty($matches[4])) {
  925. if (preg_match('/^\+$/', trim($matches[4]))) {
  926. $attr_target['strand'] = 1;
  927. }
  928. elseif (preg_match('/^\-$/', trim($matches[4]))) {
  929. $attr_target['strand'] = -1;
  930. }
  931. }
  932. $attr_target['organism_id'] = $this->target_organism_id ? $this->target_organism_id : $this->organism_id;
  933. $attr_target['type_id'] = $this->target_type_id ? $this->target_type_id : NULL;
  934. $attr_target['type'] = $this->target_type ? $this->target_type : NULL;
  935. // If this Target aligns to a feature where the match type is specified
  936. // (e.g. cDNA_match, EST_match, etc.) then we can pull the type for
  937. // the target feature from the feature type.
  938. if (preg_match('/(.+)_match/', $ret['type'], $matches)) {
  939. $attr_target['type'] = $matches[1];
  940. $attr_target['type_id'] = $this->getTypeID($matches[1], FALSE);
  941. }
  942. }
  943. else {
  944. throw new Exception(t('The "Target" attribute is incorreclty formatted for the feature "%uniquename."',
  945. ['%uniquename' => $ret['uniquename']]));
  946. }
  947. }
  948. elseif (strcmp($tag_name, 'target_organism') == 0) {
  949. $attr_target['organism_id'] = $this->findOrganism($tags[$tag_name][0], $this->current_line);
  950. }
  951. elseif (strcmp($tag_name, 'target_type') == 0) {
  952. $attr_target['type'] = $tags[$tag_name][0];
  953. $attr_target['type_id'] = $this->getTypeID($tags[$tag_name][0], FALSE);
  954. }
  955. // Get the list of non-reserved attributes these will get added
  956. // as properties to the featureprop table. The 'Note', 'Gap', 'Is_Circular',
  957. // attributes will go in as a property so those are not in the list
  958. // checked below.
  959. elseif (strcmp($tag_name, 'Name') !=0 and strcmp($tag_name, 'ID') !=0 and
  960. strcmp($tag_name, 'Alias') != 0 and strcmp($tag_name, 'Parent') != 0 and
  961. strcmp($tag_name, 'Target') != 0 and strcmp($tag_name, 'Derives_from') != 0 and
  962. strcmp($tag_name, 'Dbxref') != 0 and strcmp($tag_name, 'Ontology_term') != 0 and
  963. strcmp($tag_name, 'target_organism') != 0 and strcmp($tag_name, 'target_type') != 0 and
  964. strcmp($tag_name, 'organism' != 0)) {
  965. foreach ($tags[$tag_name] as $value) {
  966. if (!array_key_exists($tag_name, $attr_others)) {
  967. $attr_others[$tag_name] = [];
  968. }
  969. $attr_others[$tag_name][] = $value;
  970. }
  971. }
  972. }
  973. // A feature may get ignored. But let's default this to FALSE.
  974. $ret['skipped'] = FALSE;
  975. // A line may have more than one feature (e.g. match, EST_match, etc).
  976. // This flag, when TRUE, tells the parseGFF3 function to repeat this line.
  977. $ret['repeat'] = FALSE;
  978. // If neither name nor uniquename are provided then generate one.
  979. $names = $this->getFeatureNames($tags, $ret['type'], $ret['landmark'], $ret['start'], $ret['stop']);
  980. $attr_uniquename = $names['uniquename'];
  981. $attr_name = $names['name'];
  982. // If this is a match feature (match, EST_match, cDNA_match, etc), then
  983. // we need to handle this line specially.
  984. if (preg_match('/match$/i', $ret['type'])) {
  985. // If the feature already exists that means we need to add a match_part
  986. // feature. If not, then we will add a flag to the results to tell
  987. // the parseGFF3 function to repeat this line, as it has two features:
  988. // the match and the match_part. All other match feature with the same
  989. // ID in the GFF3 will just be match_part features.
  990. $parent_check = preg_replace('/_part_\d+/', '', $attr_uniquename);
  991. if (array_key_exists($parent_check, $this->features)) {
  992. // Set the match_part parent
  993. // remove the "_part_X" suffix added by the getFeatureNames to find
  994. // the parent.
  995. $attr_parent = $parent_check;
  996. $ret['type'] = 'match_part';
  997. }
  998. else {
  999. // Unset all attributes as these belong on the match_part
  1000. $attr_dbxref = [];
  1001. $attr_aliases = [];
  1002. $attr_terms = [];
  1003. $attr_derives = [];
  1004. $attr_others = [];
  1005. $ret['repeat'] = TRUE;
  1006. }
  1007. }
  1008. $ret['name'] = $attr_name;
  1009. $ret['uniquename'] = $attr_uniquename;
  1010. $ret['synonyms'] = $attr_aliases;
  1011. // Add in the dbxref record.
  1012. $ret['dbxrefs'] = [];
  1013. foreach ($attr_dbxref as $key => $dbx) {
  1014. $parts = explode(':', $dbx, 2);
  1015. $ret['dbxrefs']["{$parts[0]}:{$parts[1]}"] = array(
  1016. 'db' => $parts[0],
  1017. 'accession' => $parts[1],
  1018. );
  1019. }
  1020. // Add in the GFF source dbxref. This is needed for GBrowse.
  1021. $ret['dbxrefs']["GFF_source:{$ret['source']}"] = array(
  1022. 'db' => 'GFF_source',
  1023. 'accession' => $ret['source'],
  1024. );
  1025. // Add in the ontology terms
  1026. $ret['terms'] = [];
  1027. foreach ($attr_terms as $key => $dbx) {
  1028. $parts = explode(':', $dbx, 2);
  1029. $ret['terms']["{$parts[0]}:{$parts[1]}"] = array(
  1030. 'db' => $parts[0],
  1031. 'accession' => $parts[1],
  1032. );
  1033. }
  1034. // Add the derives from entry.
  1035. $ret['derives_from'] = '';
  1036. if (count($attr_derives) == 1) {
  1037. $ret['derives_from'] = $attr_derives[0];
  1038. }
  1039. if (count($attr_derives) > 1) {
  1040. throw new Exception(t('Each feature can only have one "Derives_from" attribute. The feature %uniquename has more than one: %derives',
  1041. [
  1042. '%uniquename' => $ret['uniquename'],
  1043. '%derives' => $ret['derives_from'],
  1044. ]));
  1045. }
  1046. // Now add all of the attributes into the return array.
  1047. foreach ($tags as $key => $value) {
  1048. $ret['attrs'][$key] = $value;
  1049. }
  1050. // Add the organism entry, but if we don't have one for this feature
  1051. // (in the case where the target_organism attribute doesn't match
  1052. // an organism in the databse) then skip this feature.
  1053. $ret['organism'] = $attr_organism;
  1054. if (!$ret['organism']) {
  1055. $ret['skipped'] = TRUE;
  1056. }
  1057. // Add the target. If the type_id is missing then remove the targeet
  1058. // and we'll skip it.
  1059. $ret['target'] = $attr_target;
  1060. if (!array_key_exists('type', $ret['target']) or empty($ret['target'])) {
  1061. $ret['target'] = [];
  1062. }
  1063. // Make sure we only have one Gap if it exists
  1064. if (array_key_exists('Gap', $attr_others) and count($attr_others['Gap']) > 1) {
  1065. throw new Exception(t('Each feature can only have one "Gap" attribute. The feature %uniquename has more than one.',
  1066. [
  1067. '%uniquename' => $ret['uniquename'],
  1068. ]));
  1069. }
  1070. // Add the properties and parent.
  1071. $ret['properties'] = $attr_others;
  1072. $ret['parent'] = $attr_parent;
  1073. return $ret;
  1074. }
  1075. /**
  1076. * Indexes the FASTA section of the file for quick lookup.
  1077. */
  1078. private function indexFASTA() {
  1079. // Iterate through the remaining lines of the file
  1080. while ($line = fgets($this->gff_file_h)) {
  1081. $this->current_line++;
  1082. $this->addItemsHandled(drupal_strlen($line));
  1083. // Get the ID and the current file pointer and store that for later.
  1084. if (preg_match('/^>/', $line)) {
  1085. $id = preg_replace('/^>([^\s]+).*$/', '\1', $line);
  1086. $this->residue_index[trim($id)] = ftell($this->gff_file_h);
  1087. }
  1088. }
  1089. }
  1090. /**
  1091. * Loads the actual residue information from the FASTA section of the file.
  1092. */
  1093. private function insertFeatureSeqs() {
  1094. $num_residues = count(array_keys($this->residue_index));
  1095. $this->setItemsHandled(0);
  1096. $this->setTotalItems($num_residues);
  1097. $count = 0;
  1098. foreach ($this->residue_index as $uniquename => $offset) {
  1099. // Skip this sequence if we can't match the name with a known feature
  1100. // or landmark name.
  1101. if (!(array_key_exists($uniquename, $this->features) and $this->features[$uniquename]) and
  1102. !(array_key_exists($uniquename, $this->landmarks) and $this->landmarks[$uniquename])) {
  1103. $this->logMessage('Assigning Sequence: cannot find a feature with a unique name of: "!uname". Please ensure the sequence names in the ##FASTA section use the same name as the ID in the feature in the GFF file. ',
  1104. ['!uname' => $uniquename], TRIPAL_WARNING);
  1105. $count++;
  1106. continue;
  1107. }
  1108. // Get the feature that this sequence belongs.
  1109. $feature_id = NULL;
  1110. if (array_key_exists($uniquename, $this->features)) {
  1111. $findex = $this->features[$uniquename]['findex'];
  1112. $feature = $this->getCachedFeature($findex);
  1113. $feature_id = $feature['feature_id'];
  1114. }
  1115. else {
  1116. $feature_id = $this->landmarks[$uniquename];
  1117. }
  1118. // Seek to the position in the GFF file where this sequence is housed.
  1119. // iterate through the lines and get store the value.
  1120. $residues = [];
  1121. fseek($this->gff_file_h, $offset);
  1122. while ($line = fgets($this->gff_file_h)) {
  1123. if (preg_match('/^>/', $line)) {
  1124. break;
  1125. }
  1126. $residues[] = trim($line);
  1127. }
  1128. $residues = implode('', $residues);
  1129. $values = [
  1130. 'residues' => $residues,
  1131. 'seqlen' => strlen($residues),
  1132. 'md5checksum' => md5($residues),
  1133. ];
  1134. chado_update_record('feature', ['feature_id' => $feature_id], $values);
  1135. $count++;
  1136. $this->setItemsHandled($count);
  1137. }
  1138. }
  1139. /**
  1140. * Retrieves a ChadoRecord object for the landmark feature.
  1141. *
  1142. * @param $landmark_name
  1143. * The name of the landmark to get
  1144. *
  1145. * @return
  1146. * A feature ChadoRecord object or NULL if the landmark is missing and
  1147. * $skip_on_missing is TRUE.
  1148. */
  1149. private function findLandmark($landmark_name) {
  1150. // Before performing a database query check to see if
  1151. // this landmark is already in our lookup list.
  1152. if (array_key_exists($landmark_name, $this->landmarks)) {
  1153. return $this->landmarks[$landmark_name];
  1154. }
  1155. $landmark = new ChadoRecord('feature');
  1156. $landmark->setValues([
  1157. 'organism_id' => $this->organism_id,
  1158. 'uniquename' => $landmark_name,
  1159. ]);
  1160. if ($landmark_type) {
  1161. $landmark->setValue('type_id', $landmark_type->getValue('cvterm_id'));
  1162. }
  1163. $num_found = $landmark->find();
  1164. if ($num_found == 0) {
  1165. return NULL;
  1166. }
  1167. if ($num_found > 1) {
  1168. throw new Exception(t("The landmark '%landmark' has more than one entry for this organism (%species). Did you provide a landmark type? If not, try resubmitting and providing a type." .
  1169. "Cannot continue", [
  1170. '%landmark' => $landmark_name,
  1171. '%species' => $this->organism->getValues('genus') . " " . $this->organism->getValues('species'),
  1172. ]));
  1173. }
  1174. // The landmark was found, remember it
  1175. $this->landmarks[$landmark_name] = $landmark->getID();
  1176. return $landmark;
  1177. }
  1178. /**
  1179. * Loads into the database any landmark sequences.
  1180. *
  1181. * @param $line
  1182. * The line from the GFF file that is the ##sequence-region comment.
  1183. */
  1184. private function insertHeaderLandmark($line) {
  1185. $region_matches = [];
  1186. if (preg_match('/^##sequence-region\s+(\w*?)\s+(\d+)\s+(\d+)$/i', $line, $region_matches)) {
  1187. $rid = $region_matches[1];
  1188. $landmark = $this->findLandmark($rid);
  1189. if (!$landmark) {
  1190. $rstart = $region_matches[2];
  1191. $rend = $region_matches[3];
  1192. if (!$this->landmark_type) {
  1193. throw new Exception(t('The landmark, !landmark, cannot be added becuase no landmark type was provided. Please redo the importer job and specify a landmark type.',
  1194. ['!landmark' => $rid]));
  1195. }
  1196. $this->insertLandmark($rid);
  1197. }
  1198. }
  1199. }
  1200. /**
  1201. * Loads a single landmark by name.
  1202. */
  1203. private function insertLandmark($name) {
  1204. $feature = new ChadoRecord('feature');
  1205. $residues = '';
  1206. $feature->setValues([
  1207. 'organism_id' => $this->organism->getValue('organism_id'),
  1208. 'uniquename' => $name,
  1209. 'name' => $name,
  1210. 'type_id' => $this->landmark_cvterm->getValue('cvterm_id'),
  1211. 'md5checksum' => md5($residues),
  1212. 'is_analysis' => FALSE,
  1213. 'is_obsolete' => FALSE,
  1214. ]);
  1215. $feature->insert();
  1216. $this->landmarks[$name] = $feature->getID();
  1217. }
  1218. /**
  1219. *
  1220. */
  1221. private function parseGFF3() {
  1222. $filesize = filesize($this->gff_file);
  1223. $this->setTotalItems($filesize);
  1224. // Holds a unique list of cvterms for later lookup.
  1225. $feature_cvterms = [];
  1226. $featureprop_cvterms = [];
  1227. while ($line = fgets($this->gff_file_h)) {
  1228. $this->current_line++;
  1229. $this->addItemsHandled(drupal_strlen($line));
  1230. $line = trim($line);
  1231. if ($this->current_line < $this->start_line) {
  1232. continue;
  1233. }
  1234. // If we're in the FASTA file we're at the end of the features so return.
  1235. if (preg_match('/^##FASTA/i', $line)) {
  1236. $this->indexFASTA();
  1237. continue;
  1238. }
  1239. // if at the ##sequence-region line handle it.
  1240. $matches = [];
  1241. if (preg_match('/^##sequence-region\s+(\w*?)\s+(\d+)\s+(\d+)$/i', $line, $matches)) {
  1242. $this->seq_region_headers[$matches[1]] = $line;
  1243. continue;
  1244. }
  1245. // skip comments
  1246. if (preg_match('/^#/', $line)) {
  1247. continue;
  1248. }
  1249. // skip empty lines
  1250. if (preg_match('/^\s*$/', $line)) {
  1251. continue;
  1252. }
  1253. // Parse this feature from this line of the GFF3 file.
  1254. $gff_feature = $this->parseGFF3Line($line);
  1255. $this->prepareFeature($gff_feature, $feature_cvterms, $featureprop_cvterms);
  1256. // If there is a second feature (in the case of a match) then
  1257. // repeat this line (to get the match_part).
  1258. if ($gff_feature['repeat'] === TRUE) {
  1259. $gff_feature = $this->parseGFF3Line($line);
  1260. $this->prepareFeature($gff_feature, $feature_cvterms, $featureprop_cvterms);
  1261. }
  1262. }
  1263. // Make sure we have the protein term in our list.
  1264. if (!array_key_exists('protein', $feature_cvterms) and
  1265. !array_key_exists('polypeptide', $feature_cvterms)) {
  1266. $feature_cvterms['polypeptide'] = 0;
  1267. }
  1268. // Iterate through the feature type terms and get a chado object for each.
  1269. foreach (array_keys($feature_cvterms) as $name) {
  1270. $this->getTypeID($name, FALSE);
  1271. }
  1272. // Iterate through the featureprop type terms and get a cvterm_id for
  1273. // each. If it doesn't exist then add a new record.
  1274. foreach (array_keys($featureprop_cvterms) as $name) {
  1275. $this->getTypeID($name, TRUE);
  1276. }
  1277. }
  1278. /**
  1279. * Prepare the database prior to working with the feature.
  1280. */
  1281. private function prepareFeature($gff_feature, &$feature_cvterms, &$featureprop_cvterms) {
  1282. // Add the landmark if it doesn't exist in the landmark list.
  1283. if (!array_key_exists($gff_feature['landmark'], $this->landmarks)) {
  1284. $this->landmarks[$gff_feature['landmark']] = FALSE;
  1285. }
  1286. // Organize DBs and DBXrefs for faster access later on.
  1287. foreach ($gff_feature['dbxrefs'] as $index => $info) {
  1288. if (!array_key_exists($info['db'], $this->db_lookup)) {
  1289. $this->db_lookup[$info['db']] = FALSE;
  1290. }
  1291. if (!array_key_exists($index, $this->dbxref_lookup)) {
  1292. $this->dbxref_lookup[$index] = $info;
  1293. }
  1294. }
  1295. // We want to make sure the Ontology_term attribute dbxrefs are
  1296. // also easily looked up... but we do not want to create them
  1297. // if they do not exist the precense of the 'cvterm' key will
  1298. // tell the loadDbxrefs() function to not create the term.
  1299. foreach ($gff_feature['terms'] as $index => $info) {
  1300. if (!array_key_exists($info['db'], $this->db_lookup)) {
  1301. $this->db_lookup[$info['db']] = FALSE;
  1302. }
  1303. if (!array_key_exists($index, $this->dbxref_lookup)) {
  1304. $this->dbxref_lookup[$index] = $info;
  1305. $this->dbxref_lookup[$index]['cvterm_id'] = NULL;
  1306. }
  1307. }
  1308. // Organize the CVterms for faster access later on.
  1309. if (!array_key_exists($gff_feature['type'], $feature_cvterms)) {
  1310. $feature_cvterms[$gff_feature['type']] = 0;
  1311. }
  1312. $feature_cvterms[$gff_feature['type']]++;
  1313. // Add any target feature types to the list as well.
  1314. if (array_key_exists('name', $gff_feature['target'])) {
  1315. if (!array_key_exists($gff_feature['target']['type'], $feature_cvterms)) {
  1316. $feature_cvterms[$gff_feature['target']['type']] = 0;
  1317. }
  1318. $feature_cvterms[$gff_feature['target']['type']]++;
  1319. }
  1320. // Organize the feature property types for faster access later on.
  1321. foreach ($gff_feature['properties'] as $prop_name => $value) {
  1322. if (!array_key_exists($prop_name, $featureprop_cvterms)) {
  1323. $featureprop_cvterms[$prop_name] = NULL;
  1324. }
  1325. $featureprop_cvterms[$prop_name]++;
  1326. }
  1327. // Cache the GFF feature details for later lookup.
  1328. if (strcmp($gff_feature['uniquename'], $gff_feature['landmark']) != 0) {
  1329. $this->cacheFeature($gff_feature);
  1330. }
  1331. // If this feature has a target then we need to add the target as
  1332. // new feature for insertion.
  1333. if (array_key_exists('name', $gff_feature['target'])) {
  1334. $this->addTargetFeature($gff_feature);
  1335. }
  1336. }
  1337. /**
  1338. *
  1339. */
  1340. private function findMissingProteins() {
  1341. $this->setItemsHandled(0);
  1342. $this->setTotalItems(count(array_keys($this->features)));
  1343. // Don't do anything if the user wants to skip creation of non listed
  1344. // proteins. Proteins that have actual lines in the GFF will still be
  1345. // created.
  1346. if ($this->skip_protein) {
  1347. $this->logMessage(' Skipping creation of non-specified proteins... ');
  1348. return;
  1349. }
  1350. // First, store records for which proteins need to exist. These
  1351. // will be for any parent that has a 'CDS' or 'protein' child.
  1352. $i = 0;
  1353. foreach ($this->features as $info) {
  1354. $i++;
  1355. $this->setItemsHandled($i);
  1356. $findex = $info['findex'];
  1357. $feature = $this->getCachedFeature($findex);
  1358. $type = $feature['type'];
  1359. if ($type == 'cds' or $type == 'protein' or $type == 'polypeptide') {
  1360. $parent_name = $feature['parent'];
  1361. if ($parent_name) {
  1362. if (!array_key_exists($parent_name, $this->proteins)) {
  1363. $this->proteins[$parent_name] = [];
  1364. }
  1365. if ($type == 'cds') {
  1366. $this->proteins[$parent_name]['cds'][] = $findex;
  1367. }
  1368. if ($type == 'protein' or $type == 'polypeptide') {
  1369. $this->proteins[$parent_name]['protein'] = $findex;
  1370. }
  1371. }
  1372. }
  1373. }
  1374. }
  1375. /**
  1376. * Checks the features and finds those that need proteins added.
  1377. */
  1378. private function addMissingProteins() {
  1379. $this->setItemsHandled(0);
  1380. $this->setTotalItems(count(array_keys($this->proteins)));
  1381. // Second, iterate through the protein list and for any parents that
  1382. // don't already have a protein we need to create one.
  1383. $i = 0;
  1384. foreach ($this->proteins as $parent_name => $info) {
  1385. $i++;
  1386. $this->setItemsHandled($i);
  1387. // Skip addition of any proteins that are already in the GFF file.
  1388. if (array_key_exists('protein', $info)) {
  1389. continue;
  1390. }
  1391. // If we don't have a protein
  1392. if (array_key_exists('cds', $info)) {
  1393. $start = INF;
  1394. $stop = -INF;
  1395. $start_phase = 0;
  1396. $stop_phase = 0;
  1397. // Find the starting and end CDS.
  1398. foreach ($info['cds'] as $findex) {
  1399. $cds = $this->getCachedFeature($findex);
  1400. if ($cds['start'] < $start) {
  1401. $start = $cds['start'];
  1402. $start_phase = $cds['phase'];
  1403. }
  1404. if ($cds['stop'] > $stop) {
  1405. $stop = $cds['stop'];
  1406. $stop_phase = $cds['phase'];
  1407. }
  1408. }
  1409. // Set the start of the protein to be the start of the coding
  1410. // sequence minus the phase.
  1411. if ($cds['strand'] == '-1') {
  1412. $stop -= $stop_phase;
  1413. }
  1414. else {
  1415. $start += $start_phase;
  1416. }
  1417. // Get the name for the protein
  1418. $name = $parent_name;
  1419. $uname = $parent_name . '-protein';
  1420. // If regexes are provdied then use those to create the protein name.
  1421. if ($this->re_mrna and $this->re_protein) {
  1422. $uname = preg_replace("/" . $this->re_mrna . "/", $this->re_protein, $parent_name);
  1423. }
  1424. // Now create the protein feature.
  1425. $feature = [
  1426. 'line' => $cds['line'],
  1427. 'landmark' => $cds['landmark'],
  1428. 'source' => $cds['source'],
  1429. 'type' => 'polypeptide',
  1430. 'start' => $start,
  1431. 'stop' => $stop,
  1432. 'strand' => $cds['strand'],
  1433. 'phase' => '',
  1434. 'attr' => [],
  1435. 'skipped' => FALSE,
  1436. 'name' => $name,
  1437. 'uniquename' => $uname,
  1438. 'synonyms' => [],
  1439. 'dbxrefs' => [],
  1440. 'terms' => [],
  1441. 'derives_from' => NULL,
  1442. 'organism' => $cds['organism_id'],
  1443. 'target' => [],
  1444. 'properties' => [],
  1445. 'parent' => $cds['parent'],
  1446. ];
  1447. $this->cacheFeature($feature);
  1448. }
  1449. }
  1450. }
  1451. /**
  1452. * Adds a new target feature to the feature list.
  1453. *
  1454. * @param $gff_feature
  1455. * The feature array created by the parseFeature function.
  1456. */
  1457. private function addTargetFeature($gff_feature) {
  1458. if (!array_key_exists($gff_feature['target']['name'], $this->features)) {
  1459. $feature = [
  1460. 'is_target' => TRUE,
  1461. 'line' => $this->current_line,
  1462. 'landmark' => NULL,
  1463. 'source' => $gff_feature['source'],
  1464. 'type' => $gff_feature['target']['type'],
  1465. 'start' => NULL,
  1466. 'stop' => NULL,
  1467. 'strand' => NULL,
  1468. 'phase' => NULL,
  1469. 'attr' => [],
  1470. 'skipped' => FALSE,
  1471. 'name' => $gff_feature['target']['name'],
  1472. 'uniquename' => $gff_feature['target']['name'],
  1473. 'synonyms' => [],
  1474. 'dbxrefs' => [],
  1475. 'terms' => [],
  1476. 'derives_from' => NULL,
  1477. 'organism' => $gff_feature['target']['organism_id'],
  1478. 'target' => [],
  1479. 'properties' => [],
  1480. 'parent' => '',
  1481. ];
  1482. $this->cacheFeature($feature);
  1483. }
  1484. }
  1485. /**
  1486. * Opens the cache file for read/write access.
  1487. */
  1488. private function openCacheFile() {
  1489. $temp_file = drupal_tempnam('temporary://', "TripalGFF3Import_");
  1490. $this->gff_cache_file_name = drupal_realpath($temp_file);
  1491. $this->logMessage("Opening temporary cache file: !cfile",
  1492. ['!cfile' => $this->gff_cache_file_name]);
  1493. $this->gff_cache_file = fopen($this->gff_cache_file_name, "r+");
  1494. }
  1495. /**
  1496. * Closes and cleans up the cache file.
  1497. */
  1498. private function closeCacheFile() {
  1499. fclose($this->gff_cache_file);
  1500. $this->logMessage("Removing temporary cache file: !cfile",
  1501. ['!cfile' => $this->gff_cache_file_name]);
  1502. unlink($this->gff_cache_file_name);
  1503. }
  1504. /**
  1505. * Caches the processed feature from a GFF3 file
  1506. */
  1507. private function cacheFeature($gff_feature) {
  1508. // Make sure we're at the end of the file.
  1509. fseek($this->gff_cache_file, 0, SEEK_END);
  1510. // Get the index of this location
  1511. $findex = ftell($this->gff_cache_file);
  1512. // Write the serialied array for this feature to the cache file
  1513. // and save the index into the member variable.
  1514. fwrite($this->gff_cache_file, serialize($gff_feature) . "\n");
  1515. $this->features[$gff_feature['uniquename']]['findex'] = $findex;
  1516. $this->features[$gff_feature['uniquename']]['feature_id'] = NULL;
  1517. }
  1518. /**
  1519. * Retrieves a feature using its index from the cache file.
  1520. */
  1521. private function getCachedFeature($findex) {
  1522. $retval = fseek($this->gff_cache_file, $findex);
  1523. if ($retval == -1) {
  1524. throw new Exception(t('Cannot seek to file location, !findex, in cache file !file.',
  1525. ['!findex' => $findex, '!file' -> $this->gff_cache_file]));
  1526. }
  1527. $feature = fgets($this->gff_cache_file);
  1528. $feature = unserialize($feature);
  1529. return $feature;
  1530. }
  1531. /**
  1532. * Imports the landmark features into Chado.
  1533. */
  1534. private function insertLandmarks() {
  1535. foreach ($this->landmarks as $uniquename => $feature_id) {
  1536. // If the landmark does not have an entry in the GFF lines, try to
  1537. // find or add it.
  1538. if ($feature_id === FALSE) {
  1539. // First see if there is a definition in the headers region.
  1540. if (array_key_exists($uniquename, $this->seq_region_headers)) {
  1541. $this->insertHeaderLandmark($this->seq_region_headers[$uniquename]);
  1542. }
  1543. // Second, if a landmark_type is provided then just add the landmark feature.
  1544. else if ($this->landmark_type) {
  1545. $this->insertLandmark($uniquename);
  1546. }
  1547. else {
  1548. throw new Exception(t('The landmark (reference) sequence, !landmark, is not in the database and not specified in the GFF3 file. Please either pre-load the landmark sequences or set a "Landmark Type" in the GFF importer.',
  1549. ['!landmark' => $uniquename]));
  1550. }
  1551. }
  1552. }
  1553. }
  1554. /**
  1555. * Imports the feature records into Chado.
  1556. */
  1557. private function insertFeatures() {
  1558. $batch_size = 1000;
  1559. $num_features = count(array_keys($this->features));
  1560. $num_batches = (int) ($num_features / $batch_size) + 1;
  1561. $this->setItemsHandled(0);
  1562. $this->setTotalItems($num_batches);
  1563. $init_sql = "
  1564. INSERT INTO {feature}
  1565. (uniquename, name, type_id, organism_id, residues, md5checksum,
  1566. seqlen, is_analysis, is_obsolete)
  1567. VALUES\n";
  1568. $i = 0;
  1569. $total = 0;
  1570. $batch_num = 1;
  1571. $sql = '';
  1572. $args = [];
  1573. foreach ($this->features as $uniquename => $info) {
  1574. $findex = $info['findex'];
  1575. $feature_id = $info['feature_id'];
  1576. $feature = $this->getCachedFeature($findex);
  1577. $total++;
  1578. $i++;
  1579. // Only do an insert if this feature doesn't already exist in the databse.
  1580. if (!$feature_id and !$feature['skipped']) {
  1581. $residues = '';
  1582. $type_id = $this->feature_cvterm_lookup[$feature['type']];
  1583. $sql .= "(:uniquename_$i, :name_$i, :type_id_$i, :organism_id_$i, :residues_$i, " .
  1584. " :md5checksum_$i, :seqlen_$i, FALSE, FALSE),\n";
  1585. $args[":uniquename_$i"] = $uniquename;
  1586. $args[":name_$i"] = $feature['name'];
  1587. $args[":type_id_$i"] = $type_id;
  1588. $args[":organism_id_$i"] = $feature['organism'] ? $feature['organism'] : $this->organism->getID();
  1589. $args[":residues_$i"] = $residues;
  1590. $args[":md5checksum_$i"] = $residues ? md5($residues) : '';
  1591. $args[":seqlen_$i"] = strlen($residues);
  1592. }
  1593. // If we've reached the size of the batch then let's do the insert.
  1594. if ($i == $batch_size or $total == $num_features) {
  1595. if (count($args) > 0) {
  1596. $sql = rtrim($sql, ",\n");
  1597. $sql = $init_sql . $sql;
  1598. chado_query($sql, $args);
  1599. }
  1600. $this->setItemsHandled($batch_num);
  1601. $batch_num++;
  1602. // Now reset all of the varables for the next batch.
  1603. $sql = '';
  1604. $i = 0;
  1605. $args = [];
  1606. }
  1607. }
  1608. }
  1609. /**
  1610. * Check if the features exist in the database.
  1611. */
  1612. private function findFeatures() {
  1613. $batch_size = 1000;
  1614. $num_features = count(array_keys($this->features));
  1615. $num_batches = (int) ($num_features / $batch_size) + 1;
  1616. $this->setItemsHandled(0);
  1617. $this->setTotalItems($num_batches);
  1618. $sql = "SELECT uniquename, type_id, organism_id, feature_id FROM {feature} WHERE uniquename in (:uniquenames)";
  1619. $i = 0;
  1620. $total = 0;
  1621. $batch_num = 1;
  1622. $names = [];
  1623. foreach ($this->features as $uniquename => $info) {
  1624. $feature_id = $info['feature_id'];
  1625. $total++;
  1626. if (!$feature_id) {
  1627. $i++;
  1628. $names[] = $uniquename;
  1629. }
  1630. // If we've reached the size of the batch then let's do the select.
  1631. if ($i == $batch_size or $total == $num_features) {
  1632. if (count($names) > 0) {
  1633. $args = [':uniquenames' => $names];
  1634. $results = chado_query($sql, $args);
  1635. while ($f = $results->fetchObject()) {
  1636. if (array_key_exists($f->uniquename, $this->features)) {
  1637. $matched_findex = $this->features[$f->uniquename]['findex'];
  1638. $matched_feature = $this->getCachedFeature($matched_findex);
  1639. $matched_type_id = $this->feature_cvterm_lookup[$matched_feature['type']];
  1640. $matched_organism_id = $this->organism->getID();
  1641. if ($matched_feature['organism']) {
  1642. $matched_organism_id = $matched_feature['organism'];
  1643. }
  1644. if ($matched_type_id == $f->type_id and $matched_organism_id == $f->organism_id) {
  1645. $this->features[$f->uniquename]['feature_id'] = $f->feature_id;
  1646. }
  1647. }
  1648. }
  1649. }
  1650. $this->setItemsHandled($batch_num);
  1651. $batch_num++;
  1652. // Now reset all of the varables for the next batch.
  1653. $i = 0;
  1654. $names = [];
  1655. }
  1656. }
  1657. }
  1658. /**
  1659. * Deletes all anciallary data about a feature so we can re-insert it.
  1660. */
  1661. private function deleteFeatureData() {
  1662. $batch_size = 1000;
  1663. $num_features = count(array_keys($this->features));
  1664. $num_batches = (int) ($num_features / $batch_size) + 1;
  1665. $this->setItemsHandled(0);
  1666. $this->setTotalItems($num_batches);
  1667. $sql1 = "DELETE from {featureprop} WHERE feature_id IN (:feature_ids)";
  1668. $sql2 = "DELETE from {featureloc} WHERE feature_id IN (:feature_ids)";
  1669. $sql3 = "DELETE from {feature_cvterm} WHERE feature_id IN (:feature_ids)";
  1670. $sql4 = "DELETE from {feature_dbxref} WHERE feature_id IN (:feature_ids)";
  1671. $sql5 = "DELETE from {feature_synonym} WHERE feature_id IN (:feature_ids)";
  1672. $sql6 = "DELETE from {feature_relationship} WHERE subject_id IN (:feature_ids)";
  1673. $sql7 = "DELETE from {analysisfeature} WHERE feature_id IN (:feature_ids)";
  1674. $i = 0;
  1675. $total = 0;
  1676. $batch_num = 1;
  1677. $feature_ids = [];
  1678. foreach ($this->features as $info) {
  1679. $findex = $info['findex'];
  1680. $feature_id = $info['feature_id'];
  1681. $feature = $this->getCachedFeature($findex);
  1682. $total++;
  1683. $i++;
  1684. if ($feature_id and !$feature['skipped']) {
  1685. $feature_ids[] = $feature_id;
  1686. }
  1687. // If we've reached the size of the batch then let's do the insert.
  1688. if ($i == $batch_size or $total == $num_features) {
  1689. if (count($feature_ids) > 0) {
  1690. $args = [':feature_ids' => $feature_ids];
  1691. chado_query($sql1, $args);
  1692. chado_query($sql2, $args);
  1693. chado_query($sql3, $args);
  1694. chado_query($sql4, $args);
  1695. chado_query($sql5, $args);
  1696. chado_query($sql6, $args);
  1697. chado_query($sql7, $args);
  1698. }
  1699. $this->setItemsHandled($batch_num);
  1700. $batch_num++;
  1701. // Now reset all of the varables for the next batch.
  1702. $i = 0;
  1703. $feature_ids = [];
  1704. }
  1705. }
  1706. }
  1707. /**
  1708. *
  1709. */
  1710. private function insertFeatureProps(){
  1711. $batch_size = 100;
  1712. $num_features = count(array_keys($this->features));
  1713. $num_batches = (int) ($num_features / $batch_size) + 1;
  1714. $this->setItemsHandled(0);
  1715. $this->setTotalItems($num_batches);
  1716. $init_sql = "INSERT INTO {featureprop} (feature_id, type_id, value, rank) VALUES\n";
  1717. $i = 0;
  1718. $j = 0;
  1719. $total = 0;
  1720. $batch_num = 1;
  1721. $sql = '';
  1722. $args = [];
  1723. foreach ($this->features as $uniquename => $info) {
  1724. $findex = $info['findex'];
  1725. $feature_id = $info['feature_id'];
  1726. $feature = $this->getCachedFeature($findex);
  1727. $total++;
  1728. // If the feature is not skipped
  1729. if (!$feature['skipped']) {
  1730. $i++;
  1731. // Iterate through all of the properties of this feature.
  1732. foreach ($feature['properties'] as $prop_name => $values) {
  1733. foreach ($values as $rank => $value) {
  1734. $j++;
  1735. $type_id = $this->featureprop_cvterm_lookup[strtolower($prop_name)];
  1736. $sql .= "(:feature_id_$j, :type_id_$j, :value_$j, :rank_$j),\n";
  1737. $args[":feature_id_$j"] = $feature_id;
  1738. $args[":type_id_$j"] = $type_id;
  1739. $args[":value_$j"] = $value;
  1740. $args[":rank_$j"] = $rank;
  1741. }
  1742. }
  1743. }
  1744. // If we've reached the size of the batch then let's do the insert.
  1745. if ($i == $batch_size or $total == $num_features) {
  1746. if (count($args) > 0) {
  1747. $sql = rtrim($sql, ",\n");
  1748. $sql = $init_sql . $sql;
  1749. chado_query($sql, $args);
  1750. }
  1751. $this->setItemsHandled($batch_num);
  1752. $batch_num++;
  1753. // Now reset all of the varables for the next batch.
  1754. $sql = '';
  1755. $i = 0;
  1756. $j = 0;
  1757. $args = [];
  1758. }
  1759. }
  1760. }
  1761. /**
  1762. *
  1763. */
  1764. private function insertFeatureParents(){
  1765. $batch_size = 100;
  1766. $num_parents = count(array_keys($this->parent_lookup));
  1767. $num_batches = (int) ($num_parents / $batch_size) + 1;
  1768. $this->setItemsHandled(0);
  1769. $this->setTotalItems($num_batches);
  1770. // Get the 'part_of' and 'derives_from cvterm.
  1771. $part_of = $this->getTypeID('part_of', FALSE);
  1772. $derives_from = $this->getTypeID('derives_from', FALSE);
  1773. $init_sql = "INSERT INTO {feature_relationship} (subject_id, object_id, type_id, rank) VALUES\n";
  1774. $i = 0;
  1775. $j = 0;
  1776. $total = 0;
  1777. $batch_num = 1;
  1778. $sql = '';
  1779. $args = [];
  1780. foreach ($this->parent_lookup as $parent => $starts) {
  1781. $total++;
  1782. $i++;
  1783. $parent_feature = $this->getCachedFeature($this->features[$parent]['findex']);
  1784. $parent_uniquename = $parent_feature['uniquename'];
  1785. $parent_feature_id = $this->features[$parent_uniquename]['feature_id'];
  1786. if (!$parent_feature['skipped']) {
  1787. foreach ($starts as $start => $children) {
  1788. foreach ($children as $child_findex) {
  1789. $j++;
  1790. $child_feature = $this->getCachedFeature($child_findex);
  1791. $child_uniquename = $child_feature['uniquename'];
  1792. $child_feature_id = $this->features[$child_uniquename]['feature_id'];
  1793. $type_id = $part_of;
  1794. if ($child_feature['type'] == 'polypeptide' or $child_feature['type'] == 'protein') {
  1795. $type_id = $derives_from;
  1796. }
  1797. $sql .= "(:subject_id_$j, :object_id_$j, :type_id_$j, :rank_$j),\n";
  1798. $args[":subject_id_$j"] = $child_feature_id;
  1799. $args[":object_id_$j"] = $parent_feature_id;
  1800. $args[":type_id_$j"] = $type_id;
  1801. $args[":rank_$j"] = $this->features[$child_uniquename]['rank'];
  1802. }
  1803. }
  1804. }
  1805. // If we've reached the size of the batch then let's do the insert.
  1806. if ($i == $batch_size or $total == $num_parents) {
  1807. if (count($args) > 0) {
  1808. $sql = rtrim($sql, ",\n");
  1809. $sql = $init_sql . $sql;
  1810. chado_query($sql, $args);
  1811. }
  1812. $this->setItemsHandled($batch_num);
  1813. $batch_num++;
  1814. // Now reset all of the varables for the next batch.
  1815. $sql = '';
  1816. $i = 0;
  1817. $j = 0;
  1818. $args = [];
  1819. }
  1820. }
  1821. }
  1822. /**
  1823. *
  1824. */
  1825. private function findDbxrefs() {
  1826. $batch_size = 1000;
  1827. $num_dbxrefs = count(array_keys($this->dbxref_lookup));
  1828. $num_batches = (int) ($num_dbxrefs / $batch_size) + 1;
  1829. $this->setItemsHandled(0);
  1830. $this->setTotalItems($num_batches);
  1831. // DBXrefs may be already present so we'll do an initial round of
  1832. // looking for them and then insert those that don't exist.
  1833. $init_sql = "
  1834. SELECT DB.name, DBX.db_id, DBX.accession, DBX.dbxref_id, CVT.cvterm_id
  1835. FROM {dbxref} DBX
  1836. INNER JOIN {db} DB on DB.db_id = DBX.db_id
  1837. LEFT JOIN {cvterm} CVT on DBX.dbxref_id = CVT.dbxref_id
  1838. WHERE
  1839. ";
  1840. $i = 0;
  1841. $total = 0;
  1842. $batch_num = 1;
  1843. $sql = '';
  1844. $args = [];
  1845. foreach ($this->dbxref_lookup as $xref => $info) {
  1846. $i++;
  1847. $total++;
  1848. $sql .= "(DBX.accession = :accession_$i and DBX.db_id = :db_id_$i) OR\n";
  1849. $args[":accession_$i"] = $info['accession'];
  1850. $args[":db_id_$i"] = $this->db_lookup[$info['db']];
  1851. // If we've reached the size of the batch then let's do the select.
  1852. if ($i == $batch_size or $total == $num_dbxrefs) {
  1853. $sql = rtrim($sql, " OR\n");
  1854. $sql = $init_sql . $sql;
  1855. $results = chado_query($sql, $args);
  1856. while ($dbxref = $results->fetchObject()) {
  1857. $index = $dbxref->name . ':' . $dbxref->accession;
  1858. $this->dbxref_lookup[$index]['dbxref_id'] = $dbxref->dbxref_id;
  1859. if ($dbxref->cvterm_id) {
  1860. $this->cvterm_lookup[$index] = $dbxref->cvterm_id;
  1861. $this->dbxref_lookup[$index]['cvterm_id'] = $dbxref->cvterm_id;
  1862. }
  1863. }
  1864. $this->setItemsHandled($batch_num);
  1865. $batch_num++;
  1866. // Now reset all of the varables for the next batch.
  1867. $sql = '';
  1868. $i = 0;
  1869. $j = 0;
  1870. $args = [];
  1871. }
  1872. }
  1873. }
  1874. /**
  1875. *
  1876. */
  1877. private function associateChildren() {
  1878. $this->setItemsHandled(0);
  1879. $this->setTotalItems(count(array_keys($this->features)));
  1880. // Iterate through parent-child relationships and set the ranks.
  1881. $i = 0;
  1882. foreach ($this->features as $info) {
  1883. $i++;
  1884. $feature = $this->getCachedFeature($info['findex']);
  1885. if ($feature['parent']) {
  1886. // Place features in order that they appear by their start coordinates.
  1887. $parent = $feature['parent'];
  1888. $start = $feature['start'];
  1889. // We can have multiple children that start at the same location
  1890. // so we'll store children in an array indexed by start position.
  1891. if (!array_key_exists($parent, $this->parent_lookup)) {
  1892. $this->parent_lookup[$parent] = [];
  1893. }
  1894. if (!array_key_exists($start, $this->parent_lookup[$parent])) {
  1895. $this->parent_lookup[$parent][$start] = [];
  1896. }
  1897. $this->parent_lookup[$parent][$start][] = $info['findex'];
  1898. }
  1899. $this->setItemsHandled($i);
  1900. }
  1901. }
  1902. /**
  1903. * Calculates ranks for all of the children of each feature.
  1904. *
  1905. * This function should not be executed until after features are loaded
  1906. * into the database and we have feature_ids for all of them.
  1907. */
  1908. private function calculateChildRanks() {
  1909. $this->setItemsHandled(0);
  1910. $this->setTotalItems(count(array_keys($this->parent_lookup)));
  1911. $i = 0;
  1912. foreach ($this->parent_lookup as $parent => $starts) {
  1913. $starts = array_keys($starts);
  1914. sort($starts);
  1915. $j = 0;
  1916. foreach ($starts as $start) {
  1917. foreach ($this->parent_lookup[$parent][$start] as $child_findex) {
  1918. $child = $this->getCachedFeature($child_findex);
  1919. $this->features[$child['uniquename']]['rank'] = $j;
  1920. $j++;
  1921. }
  1922. }
  1923. $this->setItemsHandled($j);
  1924. }
  1925. }
  1926. /**
  1927. *
  1928. */
  1929. private function findLandmarks() {
  1930. $batch_size = 1000;
  1931. $num_landmarks = count(array_keys($this->landmarks));
  1932. $num_batches = (int) ($num_landmarks / $batch_size) + 1;
  1933. $this->setItemsHandled(0);
  1934. $this->setTotalItems($num_batches);
  1935. $sql = "SELECT name, uniquename, feature_id FROM {feature} WHERE uniquename in (:landmarks)";
  1936. $i = 0;
  1937. $total = 0;
  1938. $batch_num = 1;
  1939. $names = [];
  1940. foreach ($this->landmarks as $landmark_name => $feature_id) {
  1941. $i++;
  1942. $total++;
  1943. // Only do an insert if this dbxref doesn't already exist in the databse.
  1944. // and this dbxref is from a Dbxref attribute not an Ontology_term attr.
  1945. if (!$feature_id) {
  1946. $names[] = $landmark_name;
  1947. }
  1948. // If we've reached the size of the batch then let's do the select.
  1949. if ($i == $batch_size or $total == $num_landmarks) {
  1950. if (count($names) > 0) {
  1951. $args = [':landmarks' => $names];
  1952. $results = chado_query($sql, $args);
  1953. while ($f = $results->fetchObject()) {
  1954. $this->landmarks[$f->uniquename] = $f->feature_id;
  1955. }
  1956. }
  1957. $this->setItemsHandled($batch_num);
  1958. $batch_num++;
  1959. // Now reset all of the varables for the next batch.
  1960. $i = 0;
  1961. $j = 0;
  1962. $names = [];
  1963. }
  1964. }
  1965. }
  1966. /**
  1967. *
  1968. */
  1969. private function insertDbxrefs() {
  1970. $batch_size = 1000;
  1971. $num_dbxrefs = count(array_keys($this->dbxref_lookup));
  1972. $num_batches = (int) ($num_dbxrefs / $batch_size) + 1;
  1973. $this->setItemsHandled(0);
  1974. $this->setTotalItems($num_batches);
  1975. $init_sql = "INSERT INTO {dbxref} (db_id, accession) VALUES\n";
  1976. $i = 0;
  1977. $total = 0;
  1978. $batch_num = 1;
  1979. $sql = '';
  1980. $args = [];
  1981. foreach ($this->dbxref_lookup as $info) {
  1982. $i++;
  1983. $total++;
  1984. // Only do an insert if this dbxref doesn't already exist in the databse.
  1985. // and this dbxref is from a Dbxref attribute not an Ontology_term attr.
  1986. if (!array_key_exists('dbxref_id', $info) and
  1987. !array_key_exists('cvterm_id', $info)) {
  1988. $sql .= "(:db_id_$i, :accession_$i),\n";
  1989. $args[":db_id_$i"] = $this->db_lookup[$info['db']];
  1990. $args[":accession_$i"] = $info['accession'];
  1991. }
  1992. // If we've reached the size of the batch then let's do the insert.
  1993. if ($i == $batch_size or $total == $num_dbxrefs) {
  1994. if (count($args) > 0) {
  1995. $sql = rtrim($sql, ",\n");
  1996. $sql = $init_sql . $sql;
  1997. chado_query($sql, $args);
  1998. }
  1999. $this->setItemsHandled($batch_num);
  2000. $batch_num++;
  2001. // Now reset all of the varables for the next batch.
  2002. $sql = '';
  2003. $i = 0;
  2004. $j = 0;
  2005. $args = [];
  2006. }
  2007. }
  2008. }
  2009. /**
  2010. *
  2011. */
  2012. private function insertFeatureDbxrefs() {
  2013. $batch_size = 100;
  2014. $num_features = count(array_keys($this->features));
  2015. $num_batches = (int) ($num_features / $batch_size) + 1;
  2016. $this->setItemsHandled(0);
  2017. $this->setTotalItems($num_batches);
  2018. // Don't need to use placeholders for this insert since we are only using integers.
  2019. $init_sql = "INSERT INTO {feature_dbxref} (feature_id, dbxref_id) VALUES \n";
  2020. $i = 0;
  2021. $j = 0;
  2022. $total = 0;
  2023. $batch_num = 1;
  2024. $sql = '';
  2025. $args = [];
  2026. foreach ($this->features as $uniquename => $info) {
  2027. $findex = $info['findex'];
  2028. $feature_id = $info['feature_id'];
  2029. $feature = $this->getCachedFeature($findex);
  2030. $total++;
  2031. // If the feature is not skipped
  2032. if (!$feature['skipped']) {
  2033. $i++;
  2034. // Iterate through all of the dbxrefs of this feature.
  2035. foreach ($feature['dbxrefs'] as $index => $details) {
  2036. $j++;
  2037. $sql .= "(:feature_id_$j, :dbxref_id_$j),\n";
  2038. $args[":feature_id_$j"] = $feature_id;
  2039. $args[":dbxref_id_$j"] = $this->dbxref_lookup[$index]['dbxref_id'];
  2040. }
  2041. }
  2042. // If we've reached the size of the batch then let's do the insert.
  2043. if ($i == $batch_size or $total == $num_features) {
  2044. if (count($args) > 0) {
  2045. $sql = rtrim($sql, ",\n");
  2046. $sql = $init_sql . $sql;
  2047. chado_query($sql, $args);
  2048. }
  2049. $this->setItemsHandled($batch_num);
  2050. $batch_num++;
  2051. // Now reset all of the varables for the next batch.
  2052. $sql = '';
  2053. $i = 0;
  2054. $j = 0;
  2055. $args = [];
  2056. }
  2057. }
  2058. }
  2059. /**
  2060. *
  2061. */
  2062. private function insertFeatureCVterms() {
  2063. $batch_size = 100;
  2064. $num_features = count(array_keys($this->features));
  2065. $num_batches = (int) ($num_features / $batch_size) + 1;
  2066. $this->setItemsHandled(0);
  2067. $this->setTotalItems($num_batches);
  2068. // Don't need to use placeholders for this insert since we are only using integers.
  2069. $init_sql = "INSERT INTO {feature_cvterm} (feature_id, cvterm_id, pub_id) VALUES \n";
  2070. $i = 0;
  2071. $j = 0;
  2072. $total = 0;
  2073. $batch_num = 1;
  2074. $sql = '';
  2075. $args = [];
  2076. foreach ($this->features as $uniquename => $info) {
  2077. $findex = $info['findex'];
  2078. $feature_id = $info['feature_id'];
  2079. $feature = $this->getCachedFeature($findex);
  2080. $total++;
  2081. // If the feature is not skipped
  2082. if (!$feature['skipped']) {
  2083. $i++;
  2084. // Iterate through all of the dbxrefs of this feature.
  2085. foreach ($feature['terms'] as $index => $info) {
  2086. $j++;
  2087. $sql .= "(:feature_id_$j, :cvterm_id_$j, :pub_id_$j),\n";
  2088. $args[":feature_id_$j"] = $feature_id;
  2089. $args[":cvterm_id_$j"] = $this->cvterm_lookup[$index];
  2090. $args[":pub_id_$j"] = $this->null_pub->pub_id;
  2091. }
  2092. }
  2093. // If we've reached the size of the batch then let's do the insert.
  2094. if ($i == $batch_size or $total == $num_features) {
  2095. if (count($args) > 0) {
  2096. $sql = rtrim($sql, ",\n");
  2097. $sql = $init_sql . $sql;
  2098. chado_query($sql, $args);
  2099. }
  2100. $this->setItemsHandled($batch_num);
  2101. $batch_num++;
  2102. // Now reset all of the varables for the next batch.
  2103. $sql = '';
  2104. $i = 0;
  2105. $j = 0;
  2106. $args = [];
  2107. }
  2108. }
  2109. }
  2110. /**
  2111. * Features that represent alignments have a second featureloc.
  2112. *
  2113. * The second featureloc entry belongs on the target sequence which
  2114. * should either exist or was added if desired by the end-user.
  2115. */
  2116. private function insertFeatureTargets() {
  2117. $batch_size = 1000;
  2118. $num_features = count(array_keys($this->features));
  2119. $num_batches = (int) ($num_features / $batch_size) + 1;
  2120. $this->setItemsHandled(0);
  2121. $this->setTotalItems($num_batches);
  2122. $init_sql = "
  2123. INSERT INTO {featureloc}
  2124. (srcfeature_id, feature_id, fmin, fmax, strand, phase, rank)
  2125. VALUES\n";
  2126. $i = 0;
  2127. $total = 0;
  2128. $batch_num = 1;
  2129. $sql = '';
  2130. $args = [];
  2131. foreach ($this->features as $info) {
  2132. $findex = $info['findex'];
  2133. $feature_id = $info['feature_id'];
  2134. $feature = $this->getCachedFeature($findex);
  2135. $total++;
  2136. $i++;
  2137. // If the feature is not skipped and has a target then insert the
  2138. // target alignment.
  2139. if (!$feature['skipped'] and array_key_exists('name', $feature['target'])) {
  2140. $tname = $feature['target']['name'];
  2141. $tfindex = $this->features[$tname]['findex'];
  2142. $tfeature_id = $this->features[$tname]['feature_id'];
  2143. $target = $this->getCachedFeature($tfindex);
  2144. // According to the Chado instructions for rank, the feature aligned
  2145. // to the landmark will have a rank of 0. The feature aligned to the
  2146. // target match will have a rank of 1.
  2147. $rank = 1;
  2148. $sql .= "(:srcfeature_id_$i, :feature_id_$i, :fmin_$i, :fmax_$i," .
  2149. " :strand_$i, :phase_$i, :rank_$i),\n";
  2150. $args[":srcfeature_id_$i"] = $tfeature_id;
  2151. $args[":feature_id_$i"] = $feature_id;
  2152. $args[":fmin_$i"] = $target['start'];
  2153. $args[":fmax_$i"] = $target['stop'];
  2154. $args[":strand_$i"] = $target['strand'];
  2155. $args[":phase_$i"] = $target['phase'] ? $target['phase'] : NULL;
  2156. $args[":rank_$i"] = $rank;
  2157. }
  2158. // If we've reached the size of the batch then let's do the insert.
  2159. if ($i == $batch_size or $total == $num_features) {
  2160. if (count($args) > 0) {
  2161. $sql = rtrim($sql, ",\n");
  2162. $sql = $init_sql . $sql;
  2163. chado_query($sql, $args);
  2164. }
  2165. $this->setItemsHandled($batch_num);
  2166. $batch_num++;
  2167. // Now reset all of the varables for the next batch.
  2168. $sql = '';
  2169. $i = 0;
  2170. $args = [];
  2171. }
  2172. }
  2173. }
  2174. /**
  2175. *
  2176. */
  2177. private function insertFeatureDerivesFrom() {
  2178. $batch_size = 100;
  2179. $num_features = count(array_keys($this->features));
  2180. $num_batches = (int) ($num_features / $batch_size) + 1;
  2181. $this->setItemsHandled(0);
  2182. $this->setTotalItems($num_batches);
  2183. // Get the 'derives_from' cvterm
  2184. $type_id = $this->getTypeID('derives_from', FALSE);
  2185. $init_sql = "INSERT INTO {feature_relationship} (subject_id, object_id, type_id, rank) VALUES\n";
  2186. $i = 0;
  2187. $j = 0;
  2188. $total = 0;
  2189. $batch_num = 1;
  2190. $sql = '';
  2191. $args = [];
  2192. foreach ($this->features as $uniquename => $info) {
  2193. $findex = $info['findex'];
  2194. $feature_id = $info['feature_id'];
  2195. $feature = $this->getCachedFeature($findex);
  2196. $total++;
  2197. $i++;
  2198. // If the feature is not skipped
  2199. if (!$feature['skipped'] and $feature['derives_from']) {
  2200. $object_id = $this->features[$feature['derives_from']]['feature_id'];
  2201. $sql .= "(:subject_id_$i, :object_id_$i, :type_id_$i, 0),\n";
  2202. $args[":subject_id_$i"] = $feature_id;
  2203. $args[":object_id_$i"] = $object_id;
  2204. $args[":type_id_$i"] = $type_id;
  2205. }
  2206. // If we've reached the size of the batch then let's do the insert.
  2207. if ($i == $batch_size or $total == $num_features) {
  2208. if (count($args) > 0) {
  2209. $sql = rtrim($sql, ",\n");
  2210. $sql = $init_sql . $sql;
  2211. chado_query($sql, $args);
  2212. }
  2213. $this->setItemsHandled($batch_num);
  2214. $batch_num++;
  2215. // Now reset all of the varables for the next batch.
  2216. $sql = '';
  2217. $i = 0;
  2218. $j = 0;
  2219. $args = [];
  2220. }
  2221. }
  2222. }
  2223. /**
  2224. *
  2225. */
  2226. private function insertFeatureLocs() {
  2227. $batch_size = 1000;
  2228. $num_features = count(array_keys($this->features));
  2229. $num_batches = (int) ($num_features / $batch_size) + 1;
  2230. $this->setItemsHandled(0);
  2231. $this->setTotalItems($num_batches);
  2232. $init_sql = "
  2233. INSERT INTO {featureloc}
  2234. (srcfeature_id, feature_id, fmin, fmax, strand, phase, rank)
  2235. VALUES\n";
  2236. $i = 0;
  2237. $total = 0;
  2238. $batch_num = 1;
  2239. $sql = '';
  2240. $args = [];
  2241. foreach ($this->features as $info) {
  2242. $findex = $info['findex'];
  2243. $feature_id = $info['feature_id'];
  2244. $feature = $this->getCachedFeature($findex);
  2245. $total++;
  2246. $i++;
  2247. // If the feature is not skipped and is not a match "target".
  2248. if (!$feature['skipped'] and !array_key_exists('is_target', $feature)) {
  2249. $sql .= "(:srcfeature_id_$i, :feature_id_$i, :fmin_$i, :fmax_$i," .
  2250. " :strand_$i, :phase_$i, :rank_$i),\n";
  2251. $args[":srcfeature_id_$i"] = $this->landmarks[$feature['landmark']];
  2252. $args[":feature_id_$i"] = $feature_id;
  2253. $args[":fmin_$i"] = $feature['start'];
  2254. $args[":fmax_$i"] = $feature['stop'];
  2255. $args[":strand_$i"] = $feature['strand'];
  2256. $args[":phase_$i"] = $feature['phase'] ? $feature['phase'] : NULL;
  2257. $args[":rank_$i"] = 0;
  2258. }
  2259. // If we've reached the size of the batch then let's do the insert.
  2260. if ($i == $batch_size or $total == $num_features) {
  2261. if (count($args) > 0) {
  2262. $sql = rtrim($sql, ",\n");
  2263. $sql = $init_sql . $sql;
  2264. chado_query($sql, $args);
  2265. }
  2266. $this->setItemsHandled($batch_num);
  2267. $batch_num++;
  2268. // Now reset all of the varables for the next batch.
  2269. $sql = '';
  2270. $i = 0;
  2271. $args = [];
  2272. }
  2273. }
  2274. }
  2275. /**
  2276. * Finds an organism from an organism attribute value.
  2277. */
  2278. private function findOrganism($organism_attr, $line_num) {
  2279. if (array_key_exists($organism_attr, $this->organism_lookup)) {
  2280. return $this->organism_lookup[$organism_attr];
  2281. }
  2282. // Get the organism object.
  2283. list($genus, $species) = explode(':', $organism_attr, 2);
  2284. $organism = new ChadoRecord('organism');
  2285. $organism->setValues([
  2286. 'genus' => $genus,
  2287. 'species' => $species
  2288. ]);
  2289. $num_found = $organism->find();
  2290. if ($num_found == 1){
  2291. $this->organism_lookup[$organism_attr] = $organism->getID();
  2292. return $organism->getID();
  2293. }
  2294. if ($num_found > 1) {
  2295. throw new Exception(t('Multiple organisms were found for the "organism" attribute, %organism, on line %line_num',
  2296. ['%organism' => $organism_attr, '%line_num' => $line_num]));
  2297. }
  2298. if ($this->create_organism) {
  2299. $organism->insert();
  2300. $this->organism_lookup[$organism_attr] = $organism->getID();
  2301. $gff_feature['organism'] = $organism->getID();
  2302. return $organism->getID();
  2303. }
  2304. return NULL;
  2305. }
  2306. /**
  2307. *
  2308. */
  2309. private function findSynonyms() {
  2310. $batch_size = 1000;
  2311. $num_features = count(array_keys($this->features));
  2312. $num_batches = (int) ($num_features / $batch_size) + 1;
  2313. $this->setItemsHandled(0);
  2314. $this->setTotalItems($num_batches);
  2315. $init_sql = "SELECT synonym_id, name FROM {synonym} WHERE \n";
  2316. $i = 0;
  2317. $j = 0;
  2318. $total = 0;
  2319. $batch_num = 1;
  2320. $sql = '';
  2321. $args = [];
  2322. $batch_synonyms = [];
  2323. foreach ($this->features as $uniquename => $info) {
  2324. $findex = $info['findex'];
  2325. $feature = $this->getCachedFeature($findex);
  2326. $i++;
  2327. $total++;
  2328. // Get all of the synonyms for this batch.
  2329. if (array_key_exists('synonyms', $feature)) {
  2330. foreach ($feature['synonyms'] as $index => $synonym) {
  2331. $batch_synonyms[] = $synonym;
  2332. }
  2333. }
  2334. // If we've reached the size of the batch then let's do the select
  2335. if ($i == $batch_size or $total == $num_features) {
  2336. $batch_synonyms = array_unique($batch_synonyms);
  2337. foreach ($batch_synonyms as $synonym) {
  2338. $j++;
  2339. if (!array_key_exists($synonym, $this->synonym_lookup)) {
  2340. $this->synonym_lookup[$synonym] = NULL;
  2341. }
  2342. if (!$this->synonym_lookup[$synonym]) {
  2343. $sql .= "(type_id = :type_id_$j AND name = :name_$j) OR\n";
  2344. $args[":type_id_$j"] = $this->exact_syn->cvterm_id;
  2345. $args[":name_$j"] = $synonym;
  2346. }
  2347. }
  2348. if (count($args) > 0) {
  2349. $sql = rtrim($sql, " OR\n");
  2350. $sql = $init_sql . $sql;
  2351. $results = chado_query($sql, $args);
  2352. while ($synonym = $results->fetchObject()) {
  2353. $this->synonym_lookup[$synonym->name] = $synonym->synonym_id;
  2354. }
  2355. }
  2356. $this->setItemsHandled($batch_num);
  2357. $batch_num++;
  2358. // Now reset all of the varables for the next batch.
  2359. $sql = '';
  2360. $i = 0;
  2361. $j = 0;
  2362. $args = [];
  2363. $batch_synonyms = [];
  2364. }
  2365. }
  2366. }
  2367. /**
  2368. *
  2369. */
  2370. private function insertSynonyms() {
  2371. $batch_size = 1000;
  2372. $num_synonyms = count(array_keys($this->synonym_lookup));
  2373. $num_batches = (int) ($num_synonyms / $batch_size) + 1;
  2374. $this->setItemsHandled(0);
  2375. $this->setTotalItems($num_batches);
  2376. $init_sql = "INSERT INTO {synonym} (type_id, name, synonym_sgml) VALUES\n";
  2377. $i = 0;
  2378. $total = 0;
  2379. $batch_num = 1;
  2380. $sql = '';
  2381. $args = [];
  2382. foreach ($this->synonym_lookup as $synonym => $synonym_id) {
  2383. $i++;
  2384. $total++;
  2385. // Only do an insert if this dbxref doesn't already exist in the databse.
  2386. if (!$synonym_id) {
  2387. $sql .= "(:type_id_$i,:name_$i, ''),\n";
  2388. $args[":type_id_$i"] = $this->exact_syn->cvterm_id;
  2389. $args[":name_$i"] = $synonym;
  2390. }
  2391. // If we've reached the size of the batch then let's do the insert.
  2392. if ($i == $batch_size or $total == $num_synonyms) {
  2393. if (count($args) > 0) {
  2394. $sql = rtrim($sql, ",\n");
  2395. $sql = $init_sql . $sql;
  2396. chado_query($sql, $args);
  2397. }
  2398. $this->setItemsHandled($batch_num);
  2399. $batch_num++;
  2400. // Now reset all of the varables for the next batch.
  2401. $sql = '';
  2402. $i = 0;
  2403. $args = [];
  2404. }
  2405. }
  2406. // Now we need to retrieve the synonyms IDs.
  2407. $this->findSynonyms();
  2408. }
  2409. /**
  2410. *
  2411. */
  2412. private function insertFeatureSynonyms(){
  2413. $batch_size = 1000;
  2414. $num_features = count(array_keys($this->features));
  2415. $num_batches = (int) ($num_features / $batch_size) + 1;
  2416. $this->setItemsHandled(0);
  2417. $this->setTotalItems($num_batches);
  2418. $init_sql = "INSERT INTO {feature_synonym} (synonym_id, feature_id, pub_id) VALUES \n";
  2419. $i = 0;
  2420. $j = 0;
  2421. $total = 0;
  2422. $batch_num = 1;
  2423. $args = [];
  2424. foreach ($this->features as $uniquename => $info) {
  2425. $findex = $info['findex'];
  2426. $feature_id = $info['feature_id'];
  2427. $feature = $this->getCachedFeature($findex);
  2428. $total++;
  2429. // If the feature is not skipped
  2430. if (!$feature['skipped']) {
  2431. $i++;
  2432. // Handle all of the synonyms for this feature.
  2433. foreach (array_unique($feature['synonyms']) as $synonym) {
  2434. $j++;
  2435. $sql .= "(:synonym_id_$j, :feature_id_$j, :pub_id_$j),\n";
  2436. $args[":synonym_id_$j"] = $this->synonym_lookup[$synonym];
  2437. $args[":feature_id_$j"] = $feature_id;
  2438. $args[":pub_id_$j"] = $this->null_pub->pub_id;
  2439. }
  2440. }
  2441. // If we've reached the size of the batch then let's do the insert.
  2442. if ($i == $batch_size or $total == $num_features) {
  2443. if (count($args) > 0) {
  2444. $sql = rtrim($sql, ",\n");
  2445. $sql = $init_sql . $sql;
  2446. chado_query($sql, $args);
  2447. }
  2448. $this->setItemsHandled($batch_num);
  2449. $batch_num++;
  2450. // Now reset all of the varables for the next batch.
  2451. $sql = '';
  2452. $i = 0;
  2453. $j = 0;
  2454. $args = [];
  2455. }
  2456. }
  2457. }
  2458. /**
  2459. * Determines the names for a feature using the ID and name attributes.
  2460. *
  2461. * @param $feature_attrs
  2462. * The associative array of attributes for the feature.
  2463. *
  2464. * @param $type
  2465. * The type of feature.
  2466. *
  2467. * @return array
  2468. * An associative array with 'uniquename' and 'name' keys.
  2469. */
  2470. private function getFeatureNames($attrs, $type, $landmark_name, $fmin, $fmax) {
  2471. $uniquename = '';
  2472. $name = '';
  2473. // If there is no ID or name then try to create a name and ID.
  2474. if (!array_key_exists('ID', $attrs) and !array_key_exists('name', $attrs)) {
  2475. // Check if an alternate ID field is suggested, if so, then use
  2476. // that for the name.
  2477. if (array_key_exists($this->alt_id_attr, $attrs)) {
  2478. $uniquename = $attrs[$this->alt_id_attr][0];
  2479. $name = $uniquename;
  2480. }
  2481. // If the row has a parent then generate a unqiue ID
  2482. elseif (array_key_exists('Parent', $attrs)) {
  2483. $uniquename = $attrs['Parent'][0] . "-" . $type . "-" .
  2484. $landmark_name . ":" . ($fmin + 1) . ".." . $fmax;
  2485. $name = $attrs['Parent'][0] . "-" . $type;
  2486. }
  2487. // Generate a unique name based on the type and location
  2488. // and set the name to simply be the type.
  2489. else {
  2490. $uniquename = $type . "-" . $landmark_name . ":" . ($fmin + 1) . ".." . $fmax;
  2491. $name = $type . "-" . $landmark_name;
  2492. }
  2493. }
  2494. elseif (!array_key_exists('Name', $attrs)) {
  2495. $uniquename = $attrs['ID'][0];
  2496. $name = $attrs['ID'][0];
  2497. }
  2498. elseif (!array_key_exists('ID', $attrs)) {
  2499. $uniquename = $attrs['Name'][0];
  2500. $name = $attrs['Name'][0];
  2501. }
  2502. else {
  2503. $uniquename = $attrs['ID'][0];
  2504. $name = $attrs['Name'][0];
  2505. }
  2506. // Does this uniquename already exist?
  2507. if (array_key_exists($uniquename, $this->features)) {
  2508. $prev_feature = $this->getCachedFeature($this->features[$uniquename]['findex']);
  2509. // A name can be duplicated for subfeatures (e.g. CDS features)
  2510. // that have the same parent but are really all the same thing.
  2511. if (array_key_exists('Parent', $attrs)) {
  2512. // Iterate through the list of similar IDs and see how many we have
  2513. // then add a numeric suffix.
  2514. $i = 2;
  2515. while (array_key_exists($uniquename . "_" . $i, $this->features)) {
  2516. $i++;
  2517. }
  2518. $uniquename = $uniquename . "_" . $i;
  2519. }
  2520. // If this is a match feature (e.g. match, EST_match, cDNA_match, etc).
  2521. // then we can accept a duplicated ID in the GFF3 file. But we
  2522. // must rename it before going into Chado. For this, we will allow
  2523. // the match feature to keep the original ID and we will create a new
  2524. // name for the match_part.
  2525. elseif (preg_match('/match$/', $type)) {
  2526. $i = 1;
  2527. $temp_uname = $uniquename;
  2528. do {
  2529. $temp_uname = $uniquename . "_part_" . $i;
  2530. $i++;
  2531. }
  2532. while (array_key_exists($temp_uname, $this->features));
  2533. $uniquename = $temp_uname;
  2534. }
  2535. // If this feature has already been added but as a target of a previous
  2536. // feature then we'll let it go through and replace the target feature.
  2537. elseif ($prev_feature['is_target'] == TRUE) {
  2538. // Do nothing.
  2539. }
  2540. else {
  2541. throw new Exception(t("A feature with the same ID exists multiple times: !uname", ['!uname' => $uniquename]));
  2542. }
  2543. }
  2544. return [
  2545. 'name' => $name,
  2546. 'uniquename' => $uniquename,
  2547. ];
  2548. }
  2549. /**
  2550. *
  2551. */
  2552. private function insertFeatureAnalysis() {
  2553. $batch_size = 1000;
  2554. $num_features = count(array_keys($this->features));
  2555. $num_batches = (int) ($num_features / $batch_size) + 1;
  2556. $this->setItemsHandled(0);
  2557. $this->setTotalItems($num_batches);
  2558. $init_sql = "INSERT INTO {analysisfeature} (feature_id, analysis_id, significance) VALUES \n";
  2559. $i = 0;
  2560. $total = 0;
  2561. $batch_num = 1;
  2562. $args = [];
  2563. foreach ($this->features as $info) {
  2564. $findex = $info['findex'];
  2565. $feature_id = $info['feature_id'];
  2566. $feature = $this->getCachedFeature($findex);
  2567. $i++;
  2568. $total++;
  2569. // If the feature is not skipped then add it to the table
  2570. if (!$feature['skipped']) {
  2571. $sql .= "(:feature_id_$i, :analysis_id_$i, :significance_$i),\n";
  2572. $args[":feature_id_$i"] = $feature_id;
  2573. $args[":analysis_id_$i"] = $this->analysis->getID();
  2574. if (strcmp($feature['score'], '.') != 0) {
  2575. $args[":significance_$i"] = $feature['score'];
  2576. }
  2577. else {
  2578. $args[":significance_$i"] = NULL;
  2579. }
  2580. }
  2581. // If we've reached the size of the batch then let's do the insert.
  2582. if ($i == $batch_size or $total == $num_features) {
  2583. if (count($args) > 0) {
  2584. $sql = rtrim($sql, ",\n");
  2585. $sql = $init_sql . $sql;
  2586. chado_query($sql, $args);
  2587. }
  2588. $this->setItemsHandled($batch_num);
  2589. $batch_num++;
  2590. // Now reset all of the varables for the next batch.
  2591. $sql = '';
  2592. $i = 0;
  2593. $args = [];
  2594. }
  2595. }
  2596. }
  2597. }