tripal_feature.gff_loader.inc 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207
  1. <?php
  2. /**
  3. * @file
  4. * Provides gff3 loading functionality. Creates features based on their specification
  5. * in a GFF3 file.
  6. */
  7. /**
  8. * @defgroup gff3_loader GFF3 Feature Loader
  9. * @ingroup tripal_feature
  10. * @{
  11. * Provides gff3 loading functionality. Creates features based on their specification in a GFF3 file.
  12. * @}
  13. */
  14. /**
  15. * The form to submit a GFF3 loading job
  16. *
  17. * @ingroup gff3_loader
  18. */
  19. function tripal_feature_gff3_load_form() {
  20. $form['gff_file']= array(
  21. '#type' => 'textfield',
  22. '#title' => t('GFF3 File'),
  23. '#description' => t('Please enter the full system path for the GFF file, or a path within the Drupal
  24. installation (e.g. /sites/default/files/xyz.gff). The path must be accessible to the
  25. server on which this Drupal instance is running.'),
  26. '#required' => TRUE,
  27. );
  28. // get the list of organisms
  29. $sql = "SELECT * FROM {organism} ORDER BY genus, species";
  30. $org_rset = chado_query($sql);
  31. $organisms = array();
  32. $organisms[''] = '';
  33. while ($organism = $org_rset->fetchObject()) {
  34. $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
  35. }
  36. $form['organism_id'] = array(
  37. '#title' => t('Organism'),
  38. '#type' => t('select'),
  39. '#description' => t("Choose the organism to which these sequences are associated"),
  40. '#required' => TRUE,
  41. '#options' => $organisms,
  42. );
  43. // get the list of analyses
  44. $sql = "SELECT * FROM {analysis} ORDER BY name";
  45. $org_rset = chado_query($sql);
  46. $analyses = array();
  47. $analyses[''] = '';
  48. while ($analysis = $org_rset->fetchObject()) {
  49. $analyses[$analysis->analysis_id] = "$analysis->name ($analysis->program $analysis->programversion, $analysis->sourcename)";
  50. }
  51. $form['analysis_id'] = array(
  52. '#title' => t('Analysis'),
  53. '#type' => t('select'),
  54. '#description' => t("Choose the analysis to which these features are associated.
  55. Why specify an analysis for a data load? All data comes
  56. from some place, even if downloaded from Genbank. By specifying
  57. analysis details for all data imports it allows an end user to reproduce the
  58. data set, but at least indicates the source of the data."),
  59. '#required' => TRUE,
  60. '#options' => $analyses,
  61. );
  62. $form['line_number']= array(
  63. '#type' => 'textfield',
  64. '#title' => t('Start Line Number'),
  65. '#description' => t('Enter the line number in the GFF file where you would like to begin processing. The
  66. first line is line number 1. This option is useful for examining loading problems with large GFF files.'),
  67. '#size' => 10,
  68. );
  69. $form['landmark_type'] = array(
  70. '#title' => t('Landmark Type'),
  71. '#type' => t('textfield'),
  72. '#description' => t("Optional. Use this field to specify a Sequence Ontology type
  73. for the landmark sequences in the GFF fie (e.g. 'chromosome'). If the GFF file
  74. contains a '##sequence-region' line that describes the landmark sequences to
  75. which all others are aligned and a type is provided here then the features
  76. will be created if they do not already exist. If they do exist then this
  77. field is not used."),
  78. );
  79. $form['alt_id_attr'] = array(
  80. '#title' => t('ID Attribute'),
  81. '#type' => t('textfield'),
  82. '#description' => t("Optional. Sometimes lines in the GFF file are missing the
  83. required ID attribute that specifies the unique name of the feature, but there
  84. may be another attribute that can uniquely identify the feature. If so,
  85. you may specify the name of the attribute to use for the name."),
  86. );
  87. $form['import_options'] = array(
  88. '#type' => 'fieldset',
  89. '#title' => t('Import Options'),
  90. '#collapsed' => TRUE
  91. );
  92. $form['import_options']['use_transaction']= array(
  93. '#type' => 'checkbox',
  94. '#title' => t('Use a transaction'),
  95. '#required' => FALSE,
  96. '#description' => t('Use a database transaction when loading the GFF file. If an error occurs
  97. the entire datset loaded prior to the failure will be rolled back and will not be available
  98. in the database. If this option is unchecked and failure occurs all records up to the point
  99. of failure will be present in the database.'),
  100. '#default_value' => 1,
  101. );
  102. $form['import_options']['add_only']= array(
  103. '#type' => 'checkbox',
  104. '#title' => t('Import only new features'),
  105. '#required' => FALSE,
  106. '#description' => t('The job will skip features in the GFF file that already
  107. exist in the database and import only new features.'),
  108. );
  109. $form['import_options']['update']= array(
  110. '#type' => 'checkbox',
  111. '#title' => t('Import all and update'),
  112. '#required' => FALSE,
  113. '#default_value' => 'checked',
  114. '#description' => t('Existing features will be updated and new features will be added. Attributes
  115. for a feature that are not present in the GFF but which are present in the
  116. database will not be altered.'),
  117. '#default_value' => 1,
  118. );
  119. // SPF: there are bugs in refreshing and removing features. The bugs arise
  120. // if a feature in the GFF does not have a uniquename. GenSAS will auto
  121. // generate this uniquename and it will not be the same as a previous
  122. // load because it uses the date. This causes orphaned CDS/exons, UTRs
  123. // to be left behind during a delete or refresh. So, the short term
  124. // fix is to remove these options.
  125. // $form['import_options']['refresh']= array(
  126. // '#type' => 'checkbox',
  127. // '#title' => t('Import all and replace'),
  128. // '#required' => FALSE,
  129. // '#description' => t('Existing features will be updated and feature properties not
  130. // present in the GFF file will be removed.'),
  131. // );
  132. // $form['import_options']['remove']= array(
  133. // '#type' => 'checkbox',
  134. // '#title' => t('Delete features'),
  135. // '#required' => FALSE,
  136. // '#description' => t('Features present in the GFF file that exist in the database
  137. // will be removed rather than imported'),
  138. // );
  139. $form['import_options']['create_organism']= array(
  140. '#type' => 'checkbox',
  141. '#title' => t('Create organism'),
  142. '#required' => FALSE,
  143. '#description' => t('The Tripal GFF loader supports the "organism" attribute. This allows features of a
  144. different organism to be aligned to the landmark sequence of another species. The format of the
  145. attribute is "organism=[genus]:[species]", where [genus] is the organism\'s genus and [species] is the
  146. species name. Check this box to automatically add the organism to the database if it does not already exists.
  147. Otherwise lines with an oraganism attribute where the organism is not present in the database will be skipped.'),
  148. );
  149. $form['targets'] = array(
  150. '#type' => 'fieldset',
  151. '#title' => t('Targets'),
  152. '#collapsed' => TRUE
  153. );
  154. $form['targets']['adesc'] = array(
  155. '#markup' => t("When alignments are represented in the GFF file (e.g. such as
  156. alignments of cDNA sequences to a whole genome, or blast matches), they are
  157. represented using two feature types: 'match' (or cDNA_match, EST_match, etc.)
  158. and 'match_part'. These features may also have a 'Target' attribute to
  159. specify the sequence that is being aligned.
  160. However, the organism to which the aligned sequence belongs may not be present in the
  161. GFF file. Here you can specify the organism and feature type of the target sequences.
  162. The options here will apply to all targets unless the organism and type are explicity
  163. set in the GFF file using the 'target_organism' and 'target_type' attributes."),
  164. );
  165. $form['targets']['target_organism_id'] = array(
  166. '#title' => t('Target Organism'),
  167. '#type' => t('select'),
  168. '#description' => t("Optional. Choose the organism to which target sequences belong.
  169. Select this only if target sequences belong to a different organism than the
  170. one specified above. And only choose an organism here if all of the target sequences
  171. belong to the same species. If the targets in the GFF file belong to multiple
  172. different species then the organism must be specified using the 'target_organism=genus:species'
  173. attribute in the GFF file."),
  174. '#options' => $organisms,
  175. );
  176. $form['targets']['target_type'] = array(
  177. '#title' => t('Target Type'),
  178. '#type' => t('textfield'),
  179. '#description' => t("Optional. If the unique name for a target sequence is not unique (e.g. a protein
  180. and an mRNA have the same name) then you must specify the type for all targets in the GFF file. If
  181. the targets are of different types then the type must be specified using the 'target_type=type' attribute
  182. in the GFF file. This must be a valid Sequence Ontology (SO) term."),
  183. );
  184. $form['targets']['create_target']= array(
  185. '#type' => 'checkbox',
  186. '#title' => t('Create Target'),
  187. '#required' => FALSE,
  188. '#description' => t("If the target feature cannot be found, create one using the organism and type specified above, or
  189. using the 'target_organism' and 'target_type' fields specified in the GFF file. Values specified in the
  190. GFF file take precedence over those specified above."),
  191. );
  192. $form['button'] = array(
  193. '#type' => 'submit',
  194. '#value' => t('Import GFF3 file'),
  195. '#weight' => 10,
  196. );
  197. return $form;
  198. }
  199. /**
  200. * Validate the GFF3 loading job form
  201. *
  202. * @ingroup gff3_loader
  203. */
  204. function tripal_feature_gff3_load_form_validate($form, &$form_state) {
  205. $gff_file = trim($form_state['values']['gff_file']);
  206. $organism_id = $form_state['values']['organism_id'];
  207. $target_organism_id = $form_state['values']['target_organism_id'];
  208. $target_type = trim($form_state['values']['target_type']);
  209. $create_target = $form_state['values']['create_target'];
  210. $create_organism = $form_state['values']['create_organism'];
  211. $add_only = $form_state['values']['add_only'];
  212. $update = $form_state['values']['update'];
  213. $refresh = 0; //$form_state['values']['refresh'];
  214. $remove = 0; //$form_state['values']['remove'];
  215. $use_transaction = $form_state['values']['use_transaction'];
  216. $line_number = trim($form_state['values']['line_number']);
  217. $landmark_type = trim($form_state['values']['landmark_type']);
  218. $alt_id_attr = trim($form_state['values']['alt_id_attr']);
  219. // check to see if the file is located local to Drupal
  220. $gff_file = trim($gff_file);
  221. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $gff_file;
  222. if (!file_exists($dfile)) {
  223. // if not local to Drupal, the file must be someplace else, just use
  224. // the full path provided
  225. $dfile = $gff_file;
  226. }
  227. if (!file_exists($dfile)) {
  228. form_set_error('gff_file', t("Cannot find the file on the system. Check that the file exists or that the web server has permissions to read the file."));
  229. }
  230. // @coder-ignore: there are no functions being called here
  231. if (($add_only AND ($update OR $refresh OR $remove)) OR
  232. ($update AND ($add_only OR $refresh OR $remove)) OR
  233. ($refresh AND ($update OR $add_only OR $remove)) OR
  234. ($remove AND ($update OR $refresh OR $add_only))) {
  235. form_set_error('add_only', t("Please select only one checkbox from the import options section"));
  236. }
  237. if ($line_number and !is_numeric($line_number) or $line_number < 0) {
  238. form_set_error('line_number', t("Please provide an integer line number greater than zero."));
  239. }
  240. }
  241. /**
  242. * Submit the GFF3 loading job
  243. *
  244. * @ingroup gff3_loader
  245. */
  246. function tripal_feature_gff3_load_form_submit($form, &$form_state) {
  247. global $user;
  248. $gff_file = trim($form_state['values']['gff_file']);
  249. $organism_id = $form_state['values']['organism_id'];
  250. $add_only = $form_state['values']['add_only'];
  251. $update = $form_state['values']['update'];
  252. $refresh = 0; //$form_state['values']['refresh'];
  253. $remove = 0; //$form_state['values']['remove'];
  254. $analysis_id = $form_state['values']['analysis_id'];
  255. $use_transaction = $form_state['values']['use_transaction'];
  256. $target_organism_id = $form_state['values']['target_organism_id'];
  257. $target_type = trim($form_state['values']['target_type']);
  258. $create_target = $form_state['values']['create_target'];
  259. $line_number = trim($form_state['values']['line_number']);
  260. $landmark_type = trim($form_state['values']['landmark_type']);
  261. $alt_id_attr = trim($form_state['values']['alt_id_attr']);
  262. $create_organism = $form_state['values']['create_organism'];
  263. $args = array($gff_file, $organism_id, $analysis_id, $add_only,
  264. $update, $refresh, $remove, $use_transaction, $target_organism_id,
  265. $target_type, $create_target, $line_number, $landmark_type, $alt_id_attr,
  266. $create_organism);
  267. $type = '';
  268. if ($add_only) {
  269. $type = 'import only new features';
  270. }
  271. if ($update) {
  272. $type = 'import all and update';
  273. }
  274. if ($refresh) {
  275. $type = 'import all and replace';
  276. }
  277. if ($remove) {
  278. $type = 'delete features';
  279. }
  280. $fname = preg_replace("/.*\/(.*)/", "$1", $gff_file);
  281. tripal_add_job("$type GFF3 file: $fname", 'tripal_feature',
  282. 'tripal_feature_load_gff3', $args, $user->uid);
  283. return '';
  284. }
  285. /**
  286. * Actually load a GFF3 file. This is the function called by tripal jobs
  287. *
  288. * @param $gff_file
  289. * The full path to the GFF file on the filesystem
  290. * @param $organism_id
  291. * The organism_id of the organism to which the features in the GFF belong
  292. * @param $analysis_id
  293. * The anlaysis_id of the analysis from which the features in the GFF were generated
  294. * @param $add_only
  295. * Set to 1 if feature should be added only. In the case where a feature
  296. * already exists, it will not be updated. Default is 0
  297. * @param $update
  298. * Set to 1 to update existing features. New features will be added. Attributes
  299. * for a feature that are not present in the GFF but which are present in the
  300. * database will not be altered. Default is 1
  301. * @param $refresh
  302. * Set to 1 to update existing features. New features will be added. Attributes
  303. * for a feature that are not present in the GFF but which are present in the
  304. * database will be removed. Default is 0
  305. * @param $remove
  306. * Set to 1 to remove features present in the GFF file that exist in the database.
  307. * Default is 0.
  308. * @param $use_transaction
  309. * Set to 1 to use a transaction when loading the GFF. Any failure during
  310. * loading will result in the rollback of any changes. Default is 1.
  311. * @param $target_organism_id
  312. * If the GFF file contains a 'Target' attribute then the feature and the
  313. * target will have an alignment created, but to find the proper target
  314. * feature the target organism must also be known. If different from the
  315. * organism specified for the GFF file, then use this argument to specify
  316. * the target organism. Only use this argument if all target sequences belong
  317. * to the same species. If the targets in the GFF file belong to multiple
  318. * different species then the organism must be specified using the
  319. * 'target_organism=genus:species' attribute in the GFF file. Default is NULL.
  320. * @param $target_type
  321. * If the GFF file contains a 'Target' attribute then the feature and the
  322. * target will have an alignment created, but to find the proper target
  323. * feature the target organism must also be known. This can be used to
  324. * specify the target feature type to help with identification of the target
  325. * feature. Only use this argument if all target sequences types are the same.
  326. * If the targets are of different types then the type must be specified using
  327. * the 'target_type=type' attribute in the GFF file. This must be a valid
  328. * Sequence Ontology (SO) term. Default is NULL
  329. * @param $create_target
  330. * Set to 1 to create the target feature if it cannot be found in the
  331. * database. Default is 0
  332. * @param $start_line
  333. * Set this to the line in the GFF file where importing should start. This
  334. * is useful for testing and debugging GFF files that may have problems and
  335. * you want to start at a particular line to speed testing. Default = 1
  336. * @param $landmark_type
  337. * Use this argument to specify a Sequence Ontology term name for the landmark
  338. * sequences in the GFF fie (e.g. 'chromosome'), if the GFF file contains a
  339. * '##sequence-region' line that describes the landmark sequences. Default = ''
  340. * @param $alt_id_attr
  341. * Sometimes lines in the GFF file are missing the required ID attribute that
  342. * specifies the unique name of the feature. If so, you may specify the
  343. * name of an existing attribute to use for the ID.
  344. * @param $create_organism
  345. * The Tripal GFF loader supports the "organism" attribute. This allows
  346. * features of a different organism to be aligned to the landmark sequence of
  347. * another species. The format of the attribute is "organism=[genus]:[species]",
  348. * where [genus] is the organism's genus and [species] is the species name.
  349. * Check this box to automatically add the organism to the database if it does
  350. * not already exists. Otherwise lines with an oraganism attribute where the
  351. * organism is not present in the database will be skipped.
  352. * @param $job
  353. * The tripal job_id. Only used by the Tripal Jobs subsystem.
  354. *
  355. * @ingroup gff3_loader
  356. */
  357. function tripal_feature_load_gff3($gff_file, $organism_id, $analysis_id,
  358. $add_only = 0, $update = 1, $refresh = 0, $remove = 0, $use_transaction = 1,
  359. $target_organism_id = NULL, $target_type = NULL, $create_target = 0,
  360. $start_line = 1, $landmark_type = '', $alt_id_attr = '', $create_organism = FALSE,
  361. $job = NULL) {
  362. $ret = array();
  363. $date = getdate();
  364. // empty the temp tables
  365. $sql = "DELETE FROM {tripal_gff_temp}";
  366. chado_query($sql);
  367. $sql = "DELETE FROM {tripal_gffcds_temp}";
  368. chado_query($sql);
  369. $sql = "DELETE FROM {tripal_gffprotein_temp}";
  370. chado_query($sql);
  371. // begin the transaction
  372. $transaction = null;
  373. if ($use_transaction) {
  374. $transaction = db_transaction();
  375. print "\nNOTE: Loading of this GFF file is performed using a database transaction. \n" .
  376. "If the load fails or is terminated prematurely then the entire set of \n" .
  377. "insertions/updates is rolled back and will not be found in the database\n\n";
  378. }
  379. try {
  380. // check to see if the file is located local to Drupal
  381. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $gff_file;
  382. if (!file_exists($dfile)) {
  383. // if not local to Drupal, the file must be someplace else, just use
  384. // the full path provided
  385. $dfile = $gff_file;
  386. }
  387. if (!file_exists($dfile)) {
  388. tripal_report_error('tripal_feature', TRIPAL_ERROR, "Cannot find the file: %dfile",
  389. array('%dfile' => $dfile));
  390. return 0;
  391. }
  392. print "Opening $gff_file\n";
  393. //$lines = file($dfile,FILE_SKIP_EMPTY_LINES);
  394. $fh = fopen($dfile, 'r');
  395. if (!$fh) {
  396. tripal_report_error('tripal_feature', TRIPAL_ERROR, "cannot open file: %dfile",
  397. array('%dfile' => $dfile));
  398. return 0;
  399. }
  400. $filesize = filesize($dfile);
  401. // get the controlled vocaubulary that we'll be using. The
  402. // default is the 'sequence' ontology
  403. $sql = "SELECT * FROM {cv} WHERE name = :cvname";
  404. $cv = chado_query($sql, array(':cvname' => 'sequence'))->fetchObject();
  405. if (!$cv) {
  406. tripal_report_error('tripal_feature', TRIPAL_ERROR,
  407. "Cannot find the 'sequence' ontology", array());
  408. return '';
  409. }
  410. // get the organism for which this GFF3 file belongs
  411. $sql = "SELECT * FROM {organism} WHERE organism_id = :organism_id";
  412. $organism = chado_query($sql, array(':organism_id' => $organism_id))->fetchObject();
  413. $interval = intval($filesize * 0.0001);
  414. if ($interval == 0) {
  415. $interval = 1;
  416. }
  417. $in_fasta = 0;
  418. $line_num = 0;
  419. $num_read = 0;
  420. $intv_read = 0;
  421. // prepare the statement used to get the cvterm for each feature.
  422. $sel_cvterm_sql = "
  423. SELECT CVT.cvterm_id, CVT.cv_id, CVT.name, CVT.definition,
  424. CVT.dbxref_id, CVT.is_obsolete, CVT.is_relationshiptype
  425. FROM {cvterm} CVT
  426. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  427. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  428. WHERE CV.cv_id = :cv_id and
  429. (lower(CVT.name) = lower(:name) or lower(CVTS.synonym) = lower(:synonym))
  430. ";
  431. // iterate through each line of the GFF file
  432. print "Parsing Line $line_num (0.00%). Memory: " . number_format(memory_get_usage()) . " bytes\r";
  433. while ($line = fgets($fh)) {
  434. $line_num++;
  435. $size = drupal_strlen($line);
  436. $num_read += $size;
  437. $intv_read += $size;
  438. if ($line_num < $start_line) {
  439. continue;
  440. }
  441. // update the job status every 1% features
  442. if ($job and $intv_read >= $interval) {
  443. $intv_read = 0;
  444. $percent = sprintf("%.2f", ($num_read / $filesize) * 100);
  445. print "Parsing Line $line_num (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  446. tripal_set_job_progress($job, intval(($num_read / $filesize) * 100));
  447. }
  448. // check to see if we have FASTA section, if so then set the variable
  449. // to start parsing
  450. if (preg_match('/^##FASTA/i', $line)) {
  451. print "Parsing FASTA portion...\n";
  452. if ($remove) {
  453. // we're done because this is a delete operation so break out of the loop.
  454. break;
  455. }
  456. tripal_feature_load_gff3_fasta($fh, $interval, $num_read, $intv_read, $line_num, $filesize, $job);
  457. continue;
  458. }
  459. // if the ##sequence-region line is present then we want to add a new feature
  460. if (preg_match('/^##sequence-region (.*?) (\d+) (\d+)$/i', $line, $region_matches)) {
  461. $rid = $region_matches[1];
  462. $rstart = $region_matches[2];
  463. $rend = $region_matches[3];
  464. if ($landmark_type) {
  465. $query = array(
  466. ':cv_id' => $cv->cv_id,
  467. ':name' => $landmark_type,
  468. ':synonym' => $landmark_type
  469. );
  470. $result = chado_query($sel_cvterm_sql, $query);
  471. $cvterm = $result->fetchObject();
  472. if (!$cvterm) {
  473. tripal_report_error('tripal_feature', TRIPAL_ERROR,
  474. 'cannot find feature type \'%landmark_type\' on line %line_num of the GFF file',
  475. array('%landmark_type' => $landmark_type, '%line_num' => $line_num));
  476. return '';
  477. }
  478. tripal_feature_load_gff3_feature($organism, $analysis_id, $cvterm, $rid,
  479. $rid, '', 'f', 'f', 1, 0);
  480. }
  481. continue;
  482. }
  483. // skip comments
  484. if (preg_match('/^#/', $line)) {
  485. continue;
  486. }
  487. // skip empty lines
  488. if (preg_match('/^\s*$/', $line)) {
  489. continue;
  490. }
  491. // get the columns
  492. $cols = explode("\t", $line);
  493. if (sizeof($cols) != 9) {
  494. tripal_report_error('tripal_feature', TRIPAL_ERROR, 'improper number of columns on line %line_num',
  495. array('%line_num' => $line_num));
  496. return '';
  497. }
  498. // get the column values
  499. $landmark = $cols[0];
  500. $source = $cols[1];
  501. $type = $cols[2];
  502. $start = $cols[3];
  503. $end = $cols[4];
  504. $score = $cols[5];
  505. $strand = $cols[6];
  506. $phase = $cols[7];
  507. $attrs = explode(";", $cols[8]); // split by a semicolon
  508. // ready the start and stop for chado. Chado expects these positions
  509. // to be zero-based, so we substract 1 from the fmin
  510. $fmin = $start - 1;
  511. $fmax = $end;
  512. if ($end < $start) {
  513. $fmin = $end - 1;
  514. $fmax = $start;
  515. }
  516. // format the strand for chado
  517. if (strcmp($strand, '.') == 0) {
  518. $strand = 0;
  519. }
  520. elseif (strcmp($strand, '+') == 0) {
  521. $strand = 1;
  522. }
  523. elseif (strcmp($strand, '-') == 0) {
  524. $strand = -1;
  525. }
  526. if (strcmp($phase, '.') == 0) {
  527. $phase = '';
  528. }
  529. $result = chado_query($sel_cvterm_sql, array(':cv_id' => $cv->cv_id, ':name' => $type, ':synonym' => $type));
  530. $cvterm = $result->fetchObject();
  531. if (!$cvterm) {
  532. tripal_report_error('tripal_feature', TRIPAL_ERROR, 'cannot find feature term \'%type\' on line %line_num of the GFF file',
  533. array('%type' => $type, '%line_num' => $line_num));
  534. return '';
  535. }
  536. // break apart each of the attributes
  537. $tags = array();
  538. $attr_name = '';
  539. $attr_uniquename = '';
  540. $attr_residue_info = '';
  541. $attr_locgroup = 0;
  542. $attr_fmin_partial = 'f';
  543. $attr_fmax_partial = 'f';
  544. $attr_is_obsolete = 'f';
  545. $attr_is_analysis = 'f';
  546. $attr_others = '';
  547. $residues = '';
  548. // the organism to which a feature belongs can be set in the GFF
  549. // file using the 'organism' attribute. By default we
  550. // set the $feature_organism variable to the default organism for the landmark
  551. $attr_organism = '';
  552. $feature_organism = $organism;
  553. foreach ($attrs as $attr) {
  554. $attr = rtrim($attr);
  555. $attr = ltrim($attr);
  556. if (strcmp($attr, '')==0) {
  557. continue;
  558. }
  559. if (!preg_match('/^[^\=]+\=.+$/', $attr)) {
  560. tripal_report_error('tripal_feature', TRIPAL_ERROR, 'Attribute is not correctly formatted on line %line_num: %attr',
  561. array('%line_num' => $line_num, '%attr' => $attr));
  562. return '';
  563. }
  564. // break apart each tag
  565. $tag = preg_split("/=/", $attr, 2); // split by equals sign
  566. // multiple instances of an attribute are separated by commas
  567. $tag_name = $tag[0];
  568. if (!array_key_exists($tag_name, $tags)) {
  569. $tags[$tag_name] = array();
  570. }
  571. $tags[$tag_name] = array_merge($tags[$tag_name], explode(",", $tag[1])); // split by comma
  572. // replace the URL escape codes for each tag
  573. for ($i = 0; $i < count($tags[$tag_name]); $i++) {
  574. $tags[$tag_name][$i] = urldecode($tags[$tag_name][$i]);
  575. }
  576. // get the name and ID tags
  577. $skip_feature = 0; // if there is a problem with any of the attributes this variable gets set
  578. if (strcmp($tag_name, 'ID') == 0) {
  579. $attr_uniquename = urldecode($tag[1]);
  580. }
  581. elseif (strcmp($tag_name, 'Name') == 0) {
  582. $attr_name = urldecode($tag[1]);
  583. }
  584. elseif (strcmp($tag_name, 'organism') == 0) {
  585. $attr_organism = urldecode($tag[1]);
  586. $org_matches = array();
  587. if (preg_match('/^(.*?):(.*?)$/', $attr_organism, $org_matches)) {
  588. $values = array(
  589. 'genus' => $org_matches[1],
  590. 'species' => $org_matches[2],
  591. );
  592. $org = chado_select_record('organism', array("*"), $values);
  593. if (count($org) == 0) {
  594. if ($create_organism) {
  595. $feature_organism = (object) chado_insert_record('organism', $values);
  596. if (!$feature_organism) {
  597. tripal_report_error('tripal_feature', TRIPAL_ERROR, "Could not add the organism, '%org', from line %line. Skipping this line. ",
  598. array('%org' => $attr_organism, '%line' => $line_num));
  599. $skip_feature = 1;
  600. }
  601. }
  602. else {
  603. tripal_report_error('tripal_feature', TRIPAL_ERROR, "The organism attribute '%org' on line %line does not exist. Skipping this line. ",
  604. array('%org' => $attr_organism, '%line' => $line_num));
  605. $skip_feature = 1;
  606. }
  607. }
  608. else {
  609. // We found the organism in the database so use it.
  610. $feature_organism = $org[0];
  611. }
  612. }
  613. else {
  614. tripal_report_error('tripal_feature', TRIPAL_ERROR, "The organism attribute '%org' on line %line is not properly formated. It " .
  615. "should be of the form: organism=Genus:species. Skipping this line.",
  616. array('%org' => $attr_organism, '%line' => $line_num));
  617. $skip_feature = 1;
  618. }
  619. }
  620. // Get the list of non-reserved attributes.
  621. elseif (strcmp($tag_name, 'Alias') != 0 and strcmp($tag_name, 'Parent') != 0 and
  622. strcmp($tag_name, 'Target') != 0 and strcmp($tag_name, 'Gap') != 0 and
  623. strcmp($tag_name, 'Derives_from') != 0 and strcmp($tag_name, 'Note') != 0 and
  624. strcmp($tag_name, 'Dbxref') != 0 and strcmp($tag_name, 'Ontology_term') != 0 and
  625. strcmp($tag_name, 'Is_circular') != 0 and strcmp($tag_name, 'target_organism') != 0 and
  626. strcmp($tag_name, 'target_type') != 0 and strcmp($tag_name, 'organism' != 0)) {
  627. foreach ($tags[$tag_name] as $value) {
  628. $attr_others[$tag_name][] = $value;
  629. }
  630. }
  631. }
  632. // If neither name nor uniquename are provided then generate one.
  633. if (!$attr_uniquename and !$attr_name) {
  634. // Check if an alternate ID field is suggested, if so, then use
  635. // that for the name.
  636. if (array_key_exists($alt_id_attr, $tags)) {
  637. $attr_uniquename = $tags[$alt_id_attr][0];
  638. $attr_name = $attr_uniquename;
  639. }
  640. // If the row has a parent then generate a uniquename using the parent name
  641. // add the date to the name in the event there are more than one child with
  642. // the same parent.
  643. elseif (array_key_exists('Parent', $tags)) {
  644. $attr_uniquename = $tags['Parent'][0] . "-$type-$landmark-" . $date[0] . ":" . ($fmin + 1) . ".." . $fmax;
  645. $attr_name = $attr_uniquename;
  646. }
  647. // Generate a unique name based on the date, type and location
  648. // and set the name to simply be the type.
  649. else {
  650. $attr_uniquename = $date[0] . "-$type-$landmark:" . ($fmin + 1) . ".." . $fmax;
  651. $attr_name = $type;
  652. }
  653. }
  654. // If a name is not specified then use the unique name as the name
  655. if (strcmp($attr_name, '') == 0) {
  656. $attr_name = $attr_uniquename;
  657. }
  658. // If an ID attribute is not specified then we must generate a
  659. // unique ID. Do this by combining the attribute name with the date
  660. // and line number.
  661. if (!$attr_uniquename) {
  662. $attr_uniquename = $attr_name . '-' . $date[0] . '-' . $line_num;
  663. }
  664. // Make sure the landmark sequence exists in the database. If the user
  665. // has not specified a landmark type (and it's not required in the GFF
  666. // format) then we don't know the type of the landmark so we'll hope
  667. // that it's unique across all types for the orgnaism. Only do this
  668. // test if the landmark and the feature are different.
  669. if (!$remove and !(strcmp($landmark, $attr_uniquename) == 0 or strcmp($landmark, $attr_name) == 0)) {
  670. $select = array(
  671. 'organism_id' => $organism->organism_id,
  672. 'uniquename' => $landmark,
  673. );
  674. $columns = array('count(*) as num_landmarks');
  675. if ($landmark_type) {
  676. $select['type_id'] = array(
  677. 'name' => $landmark_type,
  678. );
  679. }
  680. $count = chado_select_record('feature', $columns, $select);
  681. if (!$count or count($count) == 0 or $count[0]->num_landmarks == 0) {
  682. // now look for the landmark using the name rather than uniquename.
  683. $select = array(
  684. 'organism_id' => $organism->organism_id,
  685. 'name' => $landmark,
  686. );
  687. $columns = array('count(*) as num_landmarks');
  688. if ($landmark_type) {
  689. $select['type_id'] = array(
  690. 'name' => $landmark_type,
  691. );
  692. }
  693. $count = chado_select_record('feature', $columns, $select);
  694. if (!$count or count($count) == 0 or $count[0]->num_landmarks == 0) {
  695. tripal_report_error('tripal_feature', TRIPAL_ERROR, "The landmark '%landmark' cannot be found for this organism (%species) " .
  696. "Please add the landmark and then retry the import of this GFF3 " .
  697. "file", array('%landmark' => $landmark, '%species' => $organism->genus . " " . $organism->species));
  698. return '';
  699. }
  700. elseif ($count[0]->num_landmarks > 1) {
  701. tripal_report_error('tripal_feature', TRIPAL_ERROR, "The landmark '%landmark' has more than one entry for this organism (%species) " .
  702. "Cannot continue", array('%landmark' => $landmark, '%species' => $organism->genus . " " . $organism->species));
  703. return '';
  704. }
  705. }
  706. if ($count[0]->num_landmarks > 1) {
  707. tripal_report_error('tripal_feature', TRIPAL_ERROR, "The landmark '%landmark' is not unique for this organism. " .
  708. "The features cannot be associated", array('%landmark' => $landmark));
  709. return '';
  710. }
  711. }
  712. /*
  713. // If the option is to remove or refresh then we want to remove
  714. // the feature from the database.
  715. if ($remove or $refresh) {
  716. // Next remove the feature itself.
  717. $sql = "DELETE FROM {feature}
  718. WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
  719. $match = array(
  720. 'organism_id' => $feature_organism->organism_id,
  721. 'uniquename' => $attr_uniquename,
  722. 'type_id' => $cvterm->cvterm_id
  723. );
  724. $result = chado_delete_record('feature', $match);
  725. if (!$result) {
  726. tripal_report_error('tripal_feature', TRIPAL_ERROR, "cannot delete feature %attr_uniquename",
  727. array('%attr_uniquename' => $attr_uniquename));
  728. }
  729. $feature = 0;
  730. unset($result);
  731. }
  732. */
  733. // Add or update the feature and all properties.
  734. if ($update or $refresh or $add_only) {
  735. // Add/update the feature.
  736. $feature = tripal_feature_load_gff3_feature($feature_organism, $analysis_id, $cvterm,
  737. $attr_uniquename, $attr_name, $residues, $attr_is_analysis,
  738. $attr_is_obsolete, $add_only, $score);
  739. if ($feature) {
  740. // Add a record for this feature to the tripal_gff_temp table for
  741. // later lookup.
  742. $values = array(
  743. 'feature_id' => $feature->feature_id,
  744. 'organism_id' => $feature->organism_id,
  745. 'type_name' => $type,
  746. 'uniquename' => $feature->uniquename
  747. );
  748. // make sure this record doesn't already exist in oru temp table
  749. $results = chado_select_record('tripal_gff_temp', array('*'), $values);
  750. if (count($results) == 0) {
  751. $result = chado_insert_record('tripal_gff_temp', $values);
  752. if (!$result) {
  753. tripal_report_error('tripal_feature', TRIPAL_ERROR, "Cound not save record in temporary table, Cannot continue.", array());
  754. exit;
  755. }
  756. }
  757. // add/update the featureloc if the landmark and the ID are not the same
  758. // if they are the same then this entry in the GFF is probably a landmark identifier
  759. if (strcmp($landmark, $attr_uniquename) !=0 ) {
  760. tripal_feature_load_gff3_featureloc($feature, $organism,
  761. $landmark, $fmin, $fmax, $strand, $phase, $attr_fmin_partial,
  762. $attr_fmax_partial, $attr_residue_info, $attr_locgroup);
  763. }
  764. // add any aliases for this feature
  765. if (array_key_exists('Alias', $tags)) {
  766. tripal_feature_load_gff3_alias($feature, $tags['Alias']);
  767. }
  768. // add any dbxrefs for this feature
  769. if (array_key_exists('Dbxref', $tags)) {
  770. tripal_feature_load_gff3_dbxref($feature, $tags['Dbxref']);
  771. }
  772. // add any ontology terms for this feature
  773. if (array_key_exists('Ontology_term', $tags)) {
  774. tripal_feature_load_gff3_ontology($feature, $tags['Ontology_term']);
  775. }
  776. // add parent relationships
  777. if (array_key_exists('Parent', $tags)) {
  778. tripal_feature_load_gff3_parents($feature, $cvterm, $tags['Parent'],
  779. $feature_organism->organism_id, $strand, $phase, $fmin, $fmax);
  780. }
  781. // add target relationships
  782. if (array_key_exists('Target', $tags)) {
  783. tripal_feature_load_gff3_target($feature, $tags, $target_organism_id, $target_type, $create_target, $attr_locgroup);
  784. }
  785. // add gap information. This goes in simply as a property
  786. if (array_key_exists('Gap', $tags)) {
  787. foreach ($tags['Gap'] as $value) {
  788. tripal_feature_load_gff3_property($feature, 'Gap', $value);
  789. }
  790. }
  791. // add notes. This goes in simply as a property
  792. if (array_key_exists('Note', $tags)) {
  793. foreach ($tags['Note'] as $value) {
  794. tripal_feature_load_gff3_property($feature, 'Note', $value);
  795. }
  796. }
  797. // add the Derives_from relationship (e.g. polycistronic genes).
  798. if (array_key_exists('Derives_from', $tags)) {
  799. tripal_feature_load_gff3_derives_from($feature, $cvterm, $tags['Derives_from'][0],
  800. $feature_organism, $fmin, $fmax);
  801. }
  802. // add in the GFF3_source dbxref so that GBrowse can find the feature using the source column
  803. $source_ref = array('GFF_source:' . $source);
  804. tripal_feature_load_gff3_dbxref($feature, $source_ref);
  805. // add any additional attributes
  806. if ($attr_others) {
  807. foreach ($attr_others as $tag_name => $values) {
  808. foreach ($values as $value) {
  809. tripal_feature_load_gff3_property($feature, $tag_name, $value);
  810. }
  811. }
  812. }
  813. }
  814. }
  815. }
  816. // Do some last bit of processing.
  817. if (!$remove) {
  818. // First, add any protein sequences if needed.
  819. $sql = "SELECT feature_id FROM {tripal_gffcds_temp} LIMIT 1 OFFSET 1";
  820. $has_cds = chado_query($sql)->fetchField();
  821. if ($has_cds) {
  822. print "\nAdding protein sequences if CDS exist and no proteins in GFF...\n";
  823. $sql = "
  824. SELECT F.feature_id, F.name, F.uniquename, TGCT.strand,
  825. CVT.cvterm_id, CVT.name as feature_type,
  826. min(TGCT.fmin) as fmin, max(TGCT.fmax) as fmax,
  827. TGPT.feature_id as protein_id, TGPT.fmin as protein_fmin,
  828. TGPT.fmax as protein_fmax
  829. FROM {tripal_gffcds_temp} TGCT
  830. INNER JOIN {feature} F on F.feature_id = TGCT.parent_id
  831. INNER JOIN {cvterm} CVT on CVT.cvterm_id = F.type_id
  832. LEFT JOIN {tripal_gffprotein_temp} TGPT on TGPT.parent_id = F.feature_id
  833. GROUP BY F.feature_id, F.name, F.uniquename, CVT.cvterm_id, CVT.name,
  834. TGPT.feature_id, TGPT.fmin, TGPT.fmax, TGCT.strand
  835. ";
  836. $results = chado_query($sql);
  837. $protein_cvterm = tripal_get_cvterm(array(
  838. 'name' => 'polypeptide',
  839. 'cv_id' => array(
  840. 'name' => 'sequence'
  841. )
  842. ));
  843. while ($result = $results->fetchObject()) {
  844. // If a protein exists with this same parent then don't add a new
  845. // protein.
  846. if (!$result->protein_id) {
  847. // Get details about this protein
  848. $uname = $result->uniquename . '-protein';
  849. $name = $result->name;
  850. $values = array(
  851. 'parent_id' => $result->feature_id,
  852. 'fmin' => $result->fmin
  853. );
  854. $min_phase = chado_select_record('tripal_gffcds_temp', array('phase'), $values);
  855. $values = array(
  856. 'parent_id' => $result->feature_id,
  857. 'fmax' => $result->fmax
  858. );
  859. $max_phase = chado_select_record('tripal_gffcds_temp', array('phase'), $values);
  860. $pfmin = $result->fmin;
  861. $pfmax = $result->fmax;
  862. if ($result->strand == '-1') {
  863. $pfmax -= $max_phase[0]->phase;
  864. }
  865. else {
  866. $pfmin += $min_phase[0]->phase;
  867. }
  868. // Add the new protein record.
  869. $feature = tripal_feature_load_gff3_feature($organism, $analysis_id,
  870. $protein_cvterm, $uname, $name, '', 'f', 'f', 1, 0);
  871. // Add the derives_from relationship.
  872. $cvterm = tripal_get_cvterm(array('cvterm_id' => $result->cvterm_id));
  873. tripal_feature_load_gff3_derives_from($feature, $cvterm,
  874. $result->uniquename, $organism, $pfmin, $pfmax);
  875. // Add the featureloc record. Set the start of the protein to
  876. // be the start of the coding sequence minus the phase.
  877. tripal_feature_load_gff3_featureloc($feature, $organism, $landmark,
  878. $pfmin, $pfmax, $strand, '', 'f', 'f', '', 0);
  879. }
  880. }
  881. }
  882. print "\nSetting ranks of children...\n";
  883. // get features in a relationship that are also children of an alignment
  884. $sql = "
  885. SELECT DISTINCT F.feature_id, F.organism_id, F.type_id,
  886. F.uniquename, FL.strand
  887. FROM {tripal_gff_temp} TGT
  888. INNER JOIN {feature} F ON TGT.feature_id = F.feature_id
  889. INNER JOIN {feature_relationship} FR ON FR.object_id = TGT.feature_id
  890. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = FR.type_id
  891. INNER JOIN {featureloc} FL ON FL.feature_id = F.feature_id
  892. WHERE CVT.name = 'part_of'
  893. ";
  894. $parents = chado_query($sql);
  895. // build and prepare the SQL for selecting the children relationship
  896. $sel_gffchildren_sql = "
  897. SELECT DISTINCT FR.feature_relationship_id, FL.fmin, FR.rank
  898. FROM {feature_relationship} FR
  899. INNER JOIN {featureloc} FL on FL.feature_id = FR.subject_id
  900. WHERE FR.object_id = :feature_id ORDER BY FL.fmin ASC
  901. ";
  902. // now set the rank of any parent/child relationships. The order is based
  903. // on the fmin. The start rank is 1. This allows features with other
  904. // relationships to be '0' (the default), and doesn't interfer with the
  905. // ordering defined here.
  906. $num_recs = $parents->rowCount();
  907. $i = 1;
  908. $interval = intval($num_recs * 0.0001);
  909. if ($interval == 0) {
  910. $interval = 1;
  911. }
  912. $percent = sprintf("%.2f", ($i / $num_recs) * 100);
  913. print "Setting $i of $num_recs (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  914. while ($parent = $parents->fetchObject()) {
  915. if ($i % $interval == 0) {
  916. $percent = sprintf("%.2f", ($i / $num_recs) * 100);
  917. print "Setting $i of $num_recs (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  918. }
  919. // get the children
  920. $result = chado_query($sel_gffchildren_sql, array(':feature_id' => $parent->feature_id));
  921. // build an array of the children
  922. $children = array();
  923. while ($child = $result->fetchObject()) {
  924. $children[] = $child;
  925. }
  926. // the children list comes sorted in ascending fmin
  927. // but if the parent is on the reverse strand we need to
  928. // reverse the order of the children.
  929. if ($parent->strand == -1) {
  930. arsort($children);
  931. }
  932. // first set the ranks to a negative number so that we don't
  933. // get a duplicate error message when we try to change any of them
  934. $rank = -1;
  935. foreach ($children as $child) {
  936. $match = array('feature_relationship_id' => $child->feature_relationship_id);
  937. $values = array('rank' => $rank);
  938. chado_update_record('feature_relationship', $match, $values);
  939. $rank--;
  940. }
  941. // now set the rank correctly. The rank should start at 0.
  942. $rank = 0;
  943. foreach ($children as $child) {
  944. $match = array('feature_relationship_id' => $child->feature_relationship_id);
  945. $values = array('rank' => $rank);
  946. //print "Was: " . $child->rank . " now $rank ($parent->strand)\n" ;
  947. chado_update_record('feature_relationship', $match, $values);
  948. $rank++;
  949. }
  950. $i++;
  951. }
  952. }
  953. }
  954. catch (Exception $e) {
  955. print "\n"; // make sure we start errors on new line
  956. if ($use_transaction) {
  957. $transaction->rollback();
  958. print "FAILED: Rolling back database changes...\n";
  959. }
  960. else {
  961. print "FAILED\n";
  962. }
  963. watchdog_exception('tripal_feature', $e);
  964. return 0;
  965. }
  966. print "\nDone\n";
  967. return 1;
  968. }
  969. /**
  970. * Load the derives from attribute for a gff3 feature
  971. *
  972. * @param $feature
  973. * @param $subject
  974. * @param $organism
  975. *
  976. * @ingroup gff3_loader
  977. */
  978. function tripal_feature_load_gff3_derives_from($feature, $cvterm, $object,
  979. $organism, $fmin, $fmax) {
  980. $type = $cvterm->name;
  981. // First look for the object feature in the temp table to get it's type.
  982. $values = array(
  983. 'organism_id' => $organism->organism_id,
  984. 'uniquename' => $object,
  985. );
  986. $result = chado_select_record('tripal_gff_temp', array('type_name'), $values);
  987. $type_id = NULL;
  988. if (count($result) > 0) {
  989. $otype = tripal_get_cvterm(array(
  990. 'name' => $result[0]->type_name,
  991. 'cv_id' => array(
  992. 'name' => 'sequence'
  993. )
  994. ));
  995. if ($otype) {
  996. $type_id = $otype->cvterm_id;
  997. }
  998. }
  999. // If the object wasn't in the temp table then look for it in the
  1000. // feature table and get it's type.
  1001. if (!$type_id) {
  1002. $result = chado_select_record('feature', array('type_id'), $values);
  1003. if (count($result) > 1) {
  1004. watchdog("tripal_feature", "Cannot find feature type for, '%subject' , in 'derives_from' relationship. Multiple matching features exist with this uniquename.",
  1005. array('%subject' => $object), WATCHDOG_WARNING);
  1006. return '';
  1007. }
  1008. else if (count($result) == 0) {
  1009. watchdog("tripal_feature", "Cannot find feature type for, '%subject' , in 'derives_from' relationship.",
  1010. array('%subject' => $object), WATCHDOG_WARNING);
  1011. return '';
  1012. }
  1013. else {
  1014. $type_id = $result->type_id;
  1015. }
  1016. }
  1017. // Get the object feature.
  1018. $match = array(
  1019. 'organism_id' => $organism->organism_id,
  1020. 'uniquename' => $object,
  1021. 'type_id' => $type_id,
  1022. );
  1023. $ofeature = chado_select_record('feature', array('feature_id'), $match);
  1024. if (count($ofeature) == 0) {
  1025. tripal_report_error('tripal_feature', TRIPAL_ERROR, "Could not add 'Derives_from' relationship " .
  1026. "for %uniquename and %subject. Subject feature, '%subject', " .
  1027. "cannot be found", array('%uniquename' => $feature->uniquename, '%subject' => $subject));
  1028. return;
  1029. }
  1030. // If this feature is a protein then add it to the tripal_gffprotein_temp.
  1031. if ($type == 'protein' or $type == 'polypeptide') {
  1032. $values = array(
  1033. 'feature_id' => $feature->feature_id,
  1034. 'parent_id' => $ofeature[0]->feature_id,
  1035. 'fmin' => $fmin,
  1036. 'fmax' => $fmax
  1037. );
  1038. $result = chado_insert_record('tripal_gffprotein_temp', $values);
  1039. if (!$result) {
  1040. tripal_report_error('tripal_feature', TRIPAL_ERROR, "Cound not save record in temporary protein table, Cannot continue.", array());
  1041. exit;
  1042. }
  1043. }
  1044. // Now check to see if the relationship already exists. If it does
  1045. // then just return.
  1046. $values = array(
  1047. 'object_id' => $ofeature[0]->feature_id,
  1048. 'subject_id' => $feature->feature_id,
  1049. 'type_id' => array(
  1050. 'cv_id' => array(
  1051. 'name' => 'relationship'
  1052. ),
  1053. 'name' => 'derives_from',
  1054. ),
  1055. 'rank' => 0
  1056. );
  1057. $rel = chado_select_record('feature_relationship', array('*'), $values);
  1058. if (count($rel) > 0) {
  1059. return;
  1060. }
  1061. // finally insert the relationship if it doesn't exist
  1062. $ret = chado_insert_record('feature_relationship', $values);
  1063. if (!$ret) {
  1064. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Could not add 'Derives_from' relationship for $feature->uniquename and $subject",
  1065. array());
  1066. }
  1067. }
  1068. /**
  1069. * Load the parents for a gff3 feature
  1070. *
  1071. * @param $feature
  1072. * @param $cvterm
  1073. * @param $parents
  1074. * @param $organism_id
  1075. * @param $fmin
  1076. *
  1077. * @ingroup gff3_loader
  1078. */
  1079. function tripal_feature_load_gff3_parents($feature, $cvterm, $parents,
  1080. $organism_id, $strand, $phase, $fmin, $fmax) {
  1081. $uname = $feature->uniquename;
  1082. $type = $cvterm->name;
  1083. $rel_type = 'part_of';
  1084. // Prepare these SQL statements that will be used repeatedly.
  1085. $cvterm_sql = "
  1086. SELECT CVT.cvterm_id
  1087. FROM {cvterm} CVT
  1088. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  1089. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  1090. WHERE cv.name = :cvname and (CVT.name = :name or CVTS.synonym = :synonym)
  1091. ";
  1092. // Iterate through the parents in the list.
  1093. foreach ($parents as $parent) {
  1094. // Get the parent cvterm.
  1095. $values = array(
  1096. 'organism_id' => $organism_id,
  1097. 'uniquename' => $parent,
  1098. );
  1099. $result = chado_select_record('tripal_gff_temp', array('type_name'), $values);
  1100. if (count($result) == 0) {
  1101. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Cannot find parent: %parent", array('%parent' => $parent));
  1102. return '';
  1103. }
  1104. $parent_type = $result[0]->type_name;
  1105. // try to find the parent
  1106. $parentcvterm = chado_query($cvterm_sql, array(':cvname' => 'sequence', ':name' => $parent_type, ':synonym' => $parent_type))->fetchObject();
  1107. $relcvterm = chado_query($cvterm_sql, array(':cvname' => 'relationship', ':name' => $rel_type, ':synonym' => $rel_type))->fetchObject();
  1108. $values = array(
  1109. 'organism_id' => $organism_id,
  1110. 'uniquename' => $parent,
  1111. 'type_id' => $parentcvterm->cvterm_id,
  1112. );
  1113. $result = chado_select_record('feature', array('feature_id'), $values);
  1114. $parent_feature = $result[0];
  1115. // if the parent exists then add the relationship otherwise print error and skip
  1116. if ($parent_feature) {
  1117. // check to see if the relationship already exists
  1118. $values = array(
  1119. 'object_id' => $parent_feature->feature_id,
  1120. 'subject_id' => $feature->feature_id,
  1121. 'type_id' => $relcvterm->cvterm_id,
  1122. );
  1123. $rel = chado_select_record('feature_relationship', array('*'), $values);
  1124. if (count($rel) > 0) {
  1125. }
  1126. else {
  1127. // the relationship doesn't already exist, so add it.
  1128. $values = array(
  1129. 'subject_id' => $feature->feature_id,
  1130. 'object_id' => $parent_feature->feature_id,
  1131. 'type_id' => $relcvterm->cvterm_id,
  1132. );
  1133. $result = chado_insert_record('feature_relationship', $values);
  1134. if (!$result) {
  1135. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Failed to insert feature relationship '$uname' ($type) $rel_type '$parent' ($parent_type)",
  1136. array());
  1137. }
  1138. }
  1139. // If this feature is a CDS and now that we know the parent we can
  1140. // add it to the tripal_gffcds_temp table for later lookup.
  1141. if ($type == 'CDS') {
  1142. $values = array(
  1143. 'feature_id' => $feature->feature_id,
  1144. 'parent_id' => $parent_feature->feature_id,
  1145. 'fmin' => $fmin,
  1146. 'fmax' => $fmax,
  1147. 'strand' => $strand,
  1148. 'phase' => $phase,
  1149. );
  1150. $result = chado_insert_record('tripal_gffcds_temp', $values);
  1151. if (!$result) {
  1152. tripal_report_error('tripal_feature', TRIPAL_ERROR, "Cound not save record in temporary CDS table, Cannot continue.", array());
  1153. exit;
  1154. }
  1155. }
  1156. }
  1157. else {
  1158. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Cannot establish relationship '$uname' ($type) $rel_type '$parent' ($parent_type): Cannot find the parent",
  1159. array());
  1160. }
  1161. }
  1162. }
  1163. /**
  1164. * Load the dbxref attribute for a feature
  1165. *
  1166. * @param $feature
  1167. * @param $dbxrefs
  1168. *
  1169. * @ingroup gff3_loader
  1170. */
  1171. function tripal_feature_load_gff3_dbxref($feature, $dbxrefs) {
  1172. // iterate through each of the dbxrefs
  1173. foreach ($dbxrefs as $dbxref) {
  1174. // get the database name from the reference. If it doesn't exist then create one.
  1175. $ref = explode(":", $dbxref);
  1176. $dbname = trim($ref[0]);
  1177. $accession = trim($ref[1]);
  1178. // first look for the database name if it doesn't exist then create one.
  1179. // first check for the fully qualified URI (e.g. DB:<dbname>. If that
  1180. // can't be found then look for the name as is. If it still can't be found
  1181. // the create the database
  1182. $values = array('name' => "DB:$dbname");
  1183. $db = chado_select_record('db', array('db_id'), $values);
  1184. if (count($db) == 0) {
  1185. $values = array('name' => "$dbname");
  1186. $db = chado_select_record('db', array('db_id'), $values);
  1187. }
  1188. if (count($db) == 0) {
  1189. $values = array(
  1190. 'name' => $dbname,
  1191. 'description' => 'Added automatically by the GFF loader'
  1192. );
  1193. $success = chado_insert_record('db', $values);
  1194. if ($success) {
  1195. $values = array('name' => "$dbname");
  1196. $db = chado_select_record('db', array('db_id'), $values);
  1197. }
  1198. else {
  1199. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Cannot find or add the database $dbname", array());
  1200. return 0;
  1201. }
  1202. }
  1203. $db = $db[0];
  1204. // now check to see if the accession exists
  1205. $values = array(
  1206. 'accession' => $accession,
  1207. 'db_id' => $db->db_id
  1208. );
  1209. $dbxref = chado_select_record('dbxref', array('dbxref_id'), $values);
  1210. // if the accession doesn't exist then we want to add it
  1211. if (sizeof($dbxref) == 0) {
  1212. $values = array(
  1213. 'db_id' => $db->db_id,
  1214. 'accession' => $accession,
  1215. 'version' => ''
  1216. );
  1217. $ret = chado_insert_record('dbxref', $values);
  1218. $values = array(
  1219. 'accession' => $accession,
  1220. 'db_id' => $db->db_id
  1221. );
  1222. $dbxref = chado_select_record('dbxref', array('dbxref_id'), $values);
  1223. }
  1224. $dbxref = $dbxref[0];
  1225. // check to see if this feature dbxref already exists
  1226. $values = array(
  1227. 'dbxref_id' => $dbxref->dbxref_id,
  1228. 'feature_id' => $feature->feature_id
  1229. );
  1230. $fdbx = chado_select_record('feature_dbxref', array('feature_dbxref_id'), $values);
  1231. // now associate this feature with the database reference if it doesn't
  1232. // already exist
  1233. if (sizeof($fdbx) == 0) {
  1234. $values = array(
  1235. 'dbxref_id' => $dbxref->dbxref_id,
  1236. 'feature_id' => $feature->feature_id
  1237. );
  1238. $success = chado_insert_record('feature_dbxref', $values);
  1239. if (!$success) {
  1240. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Failed to insert Dbxref: $dbname:$accession", array());
  1241. return 0;
  1242. }
  1243. }
  1244. }
  1245. return 1;
  1246. }
  1247. /**
  1248. * Load the cvterms for a feature. Assumes there is a dbxref.accession matching a cvterm.name
  1249. *
  1250. * @param $feature
  1251. * @param $dbxrefs
  1252. *
  1253. * @ingroup gff3_loader
  1254. */
  1255. function tripal_feature_load_gff3_ontology($feature, $dbxrefs) {
  1256. // iterate through each of the dbxrefs
  1257. foreach ($dbxrefs as $dbxref) {
  1258. // get the database name from the reference. If it doesn't exist then create one.
  1259. $ref = explode(":", $dbxref);
  1260. $dbname = trim($ref[0]);
  1261. $accession = trim($ref[1]);
  1262. // first look for the database name
  1263. $db = chado_select_record('db', array('db_id'), array('name' => "DB:$dbname"));
  1264. if (sizeof($db) == 0) {
  1265. // now look for the name without the 'DB:' prefix.
  1266. $db = chado_select_record('db', array('db_id'), array('name' => "$dbname"));
  1267. if (sizeof($db) == 0) {
  1268. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Database, $dbname, is not present. Cannot associate term: $dbname:$accession", array());
  1269. return 0;
  1270. }
  1271. }
  1272. $db = $db[0];
  1273. // now check to see if the accession exists
  1274. $dbxref = chado_select_record('dbxref', array('dbxref_id'),
  1275. array('accession' => $accession, 'db_id' => $db->db_id));
  1276. if (sizeof($dbxref) == 0) {
  1277. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Accession, $accession is missing for reference: $dbname:$accession", array());
  1278. return 0;
  1279. }
  1280. $dbxref = $dbxref[0];
  1281. // now check to see if the cvterm exists
  1282. $cvterm = chado_select_record('cvterm', array('cvterm_id'), array(
  1283. 'dbxref_id' => $dbxref->dbxref_id));
  1284. // if it doesn't exist in the cvterm table, look for an alternate id
  1285. if (sizeof($cvterm) == 0) {
  1286. $cvterm = chado_select_record('cvterm_dbxref', array('cvterm_id'), array(
  1287. 'dbxref_id' => $dbxref->dbxref_id));
  1288. if (sizeof($cvterm) == 0) {
  1289. tripal_report_error("tripal_feature", TRIPAL_WARNING, "CV Term is missing for reference: $dbname:$accession", array());
  1290. return 0;
  1291. }
  1292. }
  1293. $cvterm = $cvterm[0];
  1294. // check to see if this feature cvterm already exists
  1295. $fcvt = chado_select_record('feature_cvterm', array('feature_cvterm_id'),
  1296. array('cvterm_id' => $cvterm->cvterm_id, 'feature_id' => $feature->feature_id));
  1297. // now associate this feature with the cvterm if it doesn't already exist
  1298. if (sizeof($fcvt)==0) {
  1299. $values = array(
  1300. 'cvterm_id' => $cvterm->cvterm_id,
  1301. 'feature_id' => $feature->feature_id,
  1302. 'pub_id' => array(
  1303. 'uniquename' => 'null',
  1304. ),
  1305. );
  1306. $success = chado_insert_record('feature_cvterm', $values);
  1307. if (!$success) {
  1308. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Failed to insert ontology term: $dbname:$accession", array());
  1309. return 0;
  1310. }
  1311. }
  1312. }
  1313. return 1;
  1314. }
  1315. /**
  1316. * Load any aliases for a feature
  1317. *
  1318. * @param $feature
  1319. * @param $aliases
  1320. *
  1321. * @ingroup gff3_loader
  1322. */
  1323. function tripal_feature_load_gff3_alias($feature, $aliases) {
  1324. // make sure we have a 'synonym_type' vocabulary
  1325. $select = array('name' => 'synonym_type');
  1326. $results = chado_select_record('cv', array('*'), $select);
  1327. if (count($results) == 0) {
  1328. // insert the 'synonym_type' vocabulary
  1329. $values = array(
  1330. 'name' => 'synonym_type',
  1331. 'definition' => 'vocabulary for synonym types',
  1332. );
  1333. $success = chado_insert_record('cv', $values);
  1334. if (!$success) {
  1335. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Failed to add the synonyms type vocabulary", array());
  1336. return 0;
  1337. }
  1338. // now that we've added the cv we need to get the record
  1339. $results = chado_select_record('cv', array('*'), $select);
  1340. if (count($results) > 0) {
  1341. $syncv = $results[0];
  1342. }
  1343. }
  1344. else {
  1345. $syncv = $results[0];
  1346. }
  1347. // get the 'exact' cvterm, which is the type of synonym we're adding
  1348. $select = array(
  1349. 'name' => 'exact',
  1350. 'cv_id' => array(
  1351. 'name' => 'synonym_type'
  1352. ),
  1353. );
  1354. $result = chado_select_record('cvterm', array('*'), $select);
  1355. if (count($result) == 0) {
  1356. $term = array(
  1357. 'name' => 'exact',
  1358. 'id' => "internal:exact",
  1359. 'definition' => '',
  1360. 'is_obsolete' => 0,
  1361. 'cv_name' => $syncv->name,
  1362. 'is_relationship' => FALSE
  1363. );
  1364. $syntype = tripal_insert_cvterm($term, array('update_existing' => TRUE));
  1365. if (!$syntype) {
  1366. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Cannot add synonym type: internal:$type", array());
  1367. return 0;
  1368. }
  1369. }
  1370. else {
  1371. $syntype = $result[0];
  1372. }
  1373. // iterate through all of the aliases and add each one
  1374. foreach ($aliases as $alias) {
  1375. // check to see if the alias already exists in the synonym table
  1376. // if not, then add it
  1377. $select = array(
  1378. 'name' => $alias,
  1379. 'type_id' => $syntype->cvterm_id,
  1380. );
  1381. $result = chado_select_record('synonym', array('*'), $select);
  1382. if (count($result) == 0) {
  1383. $values = array(
  1384. 'name' => $alias,
  1385. 'type_id' => $syntype->cvterm_id,
  1386. 'synonym_sgml' => '',
  1387. );
  1388. $success = chado_insert_record('synonym', $values);
  1389. if (!$success) {
  1390. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Cannot add alias $alias to synonym table", array());
  1391. return 0;
  1392. }
  1393. $result = chado_select_record('synonym', array('*'), $select);
  1394. $synonym = $result[0];
  1395. }
  1396. else {
  1397. $synonym = $result[0];
  1398. }
  1399. // check to see if we have a NULL publication in the pub table. If not,
  1400. // then add one.
  1401. $select = array('uniquename' => 'null');
  1402. $result = chado_select_record('pub', array('*'), $select);
  1403. if (count($result) == 0) {
  1404. $pub_sql = "
  1405. INSERT INTO {pub} (uniquename,type_id)
  1406. VALUES (:uname,
  1407. (SELECT cvterm_id
  1408. FROM {cvterm} CVT
  1409. INNER JOIN {dbxref} DBX ON DBX.dbxref_id = CVT.dbxref_id
  1410. INNER JOIN {db} DB ON DB.db_id = DBX.db_id
  1411. WHERE CVT.name = :type_id))
  1412. ";
  1413. $status = chado_query($psql);
  1414. if (!$status) {
  1415. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Cannot prepare statement 'ins_pub_uniquename_typeid", array());
  1416. return 0;
  1417. }
  1418. // insert the null pub
  1419. $result = chado_query($pub_sql, array(':uname' => 'null', ':type_id' => 'null'))->fetchObject();
  1420. if (!$result) {
  1421. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Cannot add null publication needed for setup of alias", array());
  1422. return 0;
  1423. }
  1424. $result = chado_select_record('pub', array('*'), $select);
  1425. $pub = $result[0];
  1426. }
  1427. else {
  1428. $pub = $result[0];
  1429. }
  1430. // check to see if the synonym exists in the feature_synonym table
  1431. // if not, then add it.
  1432. $values = array(
  1433. 'synonym_id' => $synonym->synonym_id,
  1434. 'feature_id' => $feature->feature_id,
  1435. 'pub_id' => $pub->pub_id,
  1436. );
  1437. $columns = array('feature_synonym_id');
  1438. $result = chado_select_record('feature_synonym', $columns, $values);
  1439. if (count($result) == 0) {
  1440. $values = array(
  1441. 'synonym_id' => $synonym->synonym_id,
  1442. 'feature_id' => $feature->feature_id,
  1443. 'pub_id' => $pub->pub_id,
  1444. );
  1445. $success = chado_insert_record('feature_synonym', $values);
  1446. if (!$success) {
  1447. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Cannot add alias $alias to feature synonym table", array());
  1448. return 0;
  1449. }
  1450. }
  1451. }
  1452. return 1;
  1453. }
  1454. /**
  1455. * Create the feature record & link it to it's analysis
  1456. *
  1457. * @param $organism
  1458. * @param $analysis_id
  1459. * @param $cvterm
  1460. * @param $uniquename
  1461. * @param $name
  1462. * @param $residues
  1463. * @param $is_analysis
  1464. * @param $is_obsolete
  1465. * @param $add_only
  1466. * @param $score
  1467. *
  1468. * @ingroup gff3_loader
  1469. */
  1470. function tripal_feature_load_gff3_feature($organism, $analysis_id, $cvterm, $uniquename,
  1471. $name, $residues, $is_analysis = 'f', $is_obsolete = 'f', $add_only, $score) {
  1472. // Check to see if the feature already exists.
  1473. $feature = NULL;
  1474. $fselect = array(
  1475. 'organism_id' => $organism->organism_id,
  1476. 'uniquename' => $uniquename,
  1477. 'type_id' => $cvterm->cvterm_id
  1478. );
  1479. $columns = array('feature_id', 'name', 'uniquename', 'seqlen', 'organism_id', 'type_id');
  1480. $result = chado_select_record('feature', $columns, $fselect);
  1481. if (count($result) > 0) {
  1482. $feature = $result[0];
  1483. }
  1484. if (strcmp($is_obsolete, 'f')==0 or $is_obsolete == 0) {
  1485. $is_obsolete = 'FALSE';
  1486. }
  1487. if (strcmp($is_obsolete, 't')==0 or $is_obsolete == 1) {
  1488. $is_obsolete = 'TRUE';
  1489. }
  1490. if (strcmp($is_analysis, 'f')==0 or $is_analysis == 0) {
  1491. $is_analysis = 'FALSE';
  1492. }
  1493. if (strcmp($is_analysis, 't')==0 or $is_analysis == 1) {
  1494. $is_analysis = 'TRUE';
  1495. }
  1496. // Insert the feature if it does not exist otherwise perform an update.
  1497. if (!$feature) {
  1498. $values = array(
  1499. 'organism_id' => $organism->organism_id,
  1500. 'name' => $name,
  1501. 'uniquename' => $uniquename,
  1502. // 'residues' => $residues,
  1503. // 'seqlen' => drupal_strlen($residues),
  1504. 'md5checksum' => md5($residues),
  1505. 'type_id' => $cvterm->cvterm_id,
  1506. 'is_analysis' => $is_analysis,
  1507. 'is_obsolete' => $is_obsolete,
  1508. );
  1509. $feature = (object) chado_insert_record('feature', $values);
  1510. if (!$feature) {
  1511. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Failed to insert feature '$uniquename' ($cvterm->name)", array());
  1512. return 0;
  1513. }
  1514. }
  1515. elseif (!$add_only) {
  1516. $values = array(
  1517. 'name' => $name,
  1518. // 'residues' => $residues,
  1519. // 'seqlen' => drupal_strlen($residues),
  1520. 'md5checksum' => md5($residues),
  1521. 'is_analysis' => $is_analysis,
  1522. 'is_obsolete' => $is_obsolete,
  1523. );
  1524. $match = array(
  1525. 'organism_id' => $organism->organism_id,
  1526. 'uniquename' => $uniquename,
  1527. 'type_id' => $cvterm->cvterm_id,
  1528. );
  1529. $result = chado_update_record('feature', $match, $values);
  1530. if (!$result) {
  1531. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Failed to update feature '$uniquename' ($cvterm->name)", array());
  1532. return 0;
  1533. }
  1534. }
  1535. else {
  1536. // The feature exists and we don't want to update it so return
  1537. // a value of 0. This will stop all downstream property additions
  1538. return $feature;
  1539. }
  1540. // Add the analysisfeature entry to the analysisfeature table if
  1541. // it doesn't already exist.
  1542. $af_values = array(
  1543. 'analysis_id' => $analysis_id,
  1544. 'feature_id' => $feature->feature_id
  1545. );
  1546. $afeature = chado_select_record('analysisfeature', array('analysisfeature_id'), $af_values);
  1547. if (count($afeature)==0) {
  1548. // if a score is available then set that to be the significance field
  1549. if (strcmp($score, '.') != 0) {
  1550. $af_values['significance'] = $score;
  1551. }
  1552. if (!chado_insert_record('analysisfeature', $af_values)) {
  1553. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Could not add analysisfeature record: $analysis_id, $feature->feature_id", array());
  1554. }
  1555. }
  1556. else {
  1557. // if a score is available then set that to be the significance field
  1558. $new_vals = array();
  1559. if (strcmp($score, '.')!=0) {
  1560. $new_vals['significance'] = $score;
  1561. }
  1562. else {
  1563. $new_vals['significance'] = '__NULL__';
  1564. }
  1565. if (!$add_only) {
  1566. $ret = chado_update_record('analysisfeature', $af_values, $new_vals);
  1567. if (!$ret) {
  1568. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Could not update analysisfeature record: $analysis_id, $feature->feature_id", array());
  1569. }
  1570. }
  1571. }
  1572. return $feature;
  1573. }
  1574. /**
  1575. * Insert the location of the feature
  1576. *
  1577. * @param $feature
  1578. * @param $organism
  1579. * @param $landmark
  1580. * @param $fmin
  1581. * @param $fmax
  1582. * @param $strand
  1583. * @param $phase
  1584. * @param $is_fmin_partial
  1585. * @param $is_fmax_partial
  1586. * @param $residue_info
  1587. * @param $locgroup
  1588. * @param $landmark_type_id
  1589. * @param $landmark_organism_id
  1590. * @param $create_landmark
  1591. * @param $landmark_is_target
  1592. *
  1593. * @ingroup gff3_loader
  1594. */
  1595. function tripal_feature_load_gff3_featureloc($feature, $organism, $landmark, $fmin,
  1596. $fmax, $strand, $phase, $is_fmin_partial, $is_fmax_partial, $residue_info, $locgroup,
  1597. $landmark_type_id = '', $landmark_organism_id = '', $create_landmark = 0,
  1598. $landmark_is_target = 0) {
  1599. $select = array(
  1600. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  1601. 'uniquename' => $landmark,
  1602. );
  1603. if ($landmark_type_id) {
  1604. $select['type_id'] = $landmark_type_id;
  1605. }
  1606. $results = chado_select_record('feature', array('feature_id'), $select);
  1607. $srcfeature = '';
  1608. if (count($results)==0) {
  1609. // so we couldn't find the landmark using the uniquename. Let's try the 'name'.
  1610. // if we return only a single result then we can proceed. Otherwise give an
  1611. $select = array(
  1612. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  1613. 'name' => $landmark,
  1614. );
  1615. if ($landmark_type_id) {
  1616. $select['type_id'] = $landmark_type_id;
  1617. }
  1618. $results = chado_select_record('feature', array('feature_id'), $select);
  1619. if (count($results) == 0) {
  1620. // if the landmark is the target feature in a matched alignment then try one more time to
  1621. // find it by querying any feature with the same uniquename. If we find one then use it.
  1622. if ($landmark_is_target) {
  1623. $select = array('uniquename' => $landmark);
  1624. $results = chado_select_record('feature', array('feature_id'), $select);
  1625. if (count($results) == 1) {
  1626. $srcfeature = $results[0];
  1627. }
  1628. }
  1629. if (!$srcfeature) {
  1630. // we couldn't find the landmark feature, so if the user has requested we create it then do so
  1631. // but only if we have a type id
  1632. if ($create_landmark and $landmark_type_id) {
  1633. $values = array(
  1634. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  1635. 'name' => $landmark,
  1636. 'uniquename' => $landmark,
  1637. 'type_id' => $landmark_type_id
  1638. );
  1639. $results = chado_insert_record('feature', $values);
  1640. if (!$results) {
  1641. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Cannot find landmark feature: '%landmark', nor could it be inserted",
  1642. array('%landmark' => $landmark));
  1643. return 0;
  1644. }
  1645. $srcfeature = new stdClass();
  1646. $srcfeature->feature_id = $results['feature_id'];
  1647. }
  1648. else {
  1649. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Cannot find unique landmark feature: '%landmark'.",
  1650. array('%landmark' => $landmark));
  1651. return 0;
  1652. }
  1653. }
  1654. }
  1655. elseif (count($results) > 1) {
  1656. tripal_report_error("tripal_feature", TRIPAL_WARNING, "multiple landmarks exist with the name: '%landmark'. Cannot
  1657. resolve which one to use. Cannot add the feature location record",
  1658. array('%landmark' => $landmark));
  1659. return 0;
  1660. }
  1661. else {
  1662. $srcfeature = $results[0];
  1663. }
  1664. }
  1665. elseif (count($results) > 1) {
  1666. tripal_report_error("tripal_feature", TRIPAL_WARNING, "multiple landmarks exist with the name: '%landmark'. Cannot
  1667. resolve which one to use. Cannot add the feature location record",
  1668. array('%landmark' => $landmark));
  1669. return 0;
  1670. }
  1671. else {
  1672. $srcfeature = $results[0];
  1673. }
  1674. // TODO: create an attribute that recognizes the residue_info,locgroup,
  1675. // is_fmin_partial and is_fmax_partial, right now these are
  1676. // hardcoded to be false and 0 below.
  1677. // check to see if this featureloc already exists, but also keep track of the
  1678. // last rank value
  1679. $rank = 0;
  1680. $exists = 0;
  1681. $select = array('feature_id' => $feature->feature_id);
  1682. $options = array(
  1683. 'order_by' => array(
  1684. 'rank' => 'ASC'
  1685. ),
  1686. );
  1687. $locrecs = chado_select_record('featureloc', array('*'), $select, $options);
  1688. foreach ($locrecs as $featureloc) {
  1689. // it is possible for the featureloc->srcfeature_id to be NULL. This can happen if the srcfeature
  1690. // is not known (according to chado table field descriptions). If it's null then just skip this entry
  1691. if (!$featureloc->srcfeature_id) {
  1692. continue;
  1693. }
  1694. $select = array('feature_id' => $featureloc->srcfeature_id);
  1695. $columns = array('feature_id', 'name');
  1696. $locsfeature = chado_select_record('feature', $columns, $select);
  1697. // the source feature name and at least the fmin and fmax must be the same
  1698. // for an update of the featureloc, otherwise we'll insert a new record.
  1699. if (strcmp($locsfeature[0]->name, $landmark)==0 and
  1700. ($featureloc->fmin == $fmin or $featureloc->fmax == $fmax)) {
  1701. $match = array('featureloc_id' => $featureloc->featureloc_id);
  1702. $values = array();
  1703. $exists = 1;
  1704. if ($featureloc->fmin != $fmin) {
  1705. $values['fmin'] = $fmin;
  1706. }
  1707. if ($featureloc->fmax != $fmax) {
  1708. $values['fmax'] = $fmax;
  1709. }
  1710. if ($featureloc->strand != $strand) {
  1711. $values['strand'] = $strand;
  1712. }
  1713. if (count($values) > 0) {
  1714. chado_update_record('featureloc', $match, $values);
  1715. }
  1716. }
  1717. $rank = $featureloc->rank + 1;
  1718. }
  1719. if (!$exists) {
  1720. // this feature location is new so add it
  1721. if (strcmp($is_fmin_partial, 'f')==0 or !$is_fmin_partial) {
  1722. $is_fmin_partial = 'FALSE';
  1723. }
  1724. elseif (strcmp($is_fmin_partial, 't')==0 or $is_fmin_partial = 1) {
  1725. $is_fmin_partial = 'TRUE';
  1726. }
  1727. if (strcmp($is_fmax_partial, 'f')==0 or !$is_fmax_partial) {
  1728. $is_fmax_partial = 'FALSE';
  1729. }
  1730. elseif (strcmp($is_fmax_partial, 't')==0 or $is_fmax_partial = 1) {
  1731. $is_fmax_partial = 'TRUE';
  1732. }
  1733. $values = array(
  1734. 'feature_id' => $feature->feature_id,
  1735. 'srcfeature_id' => $srcfeature->feature_id,
  1736. 'fmin' => $fmin,
  1737. 'is_fmin_partial' => $is_fmin_partial,
  1738. 'fmax' => $fmax,
  1739. 'is_fmax_partial' => $is_fmax_partial,
  1740. 'strand' => $strand,
  1741. 'residue_info' => $residue_info,
  1742. 'locgroup' => $locgroup,
  1743. 'rank' => $rank
  1744. );
  1745. if ($phase) {
  1746. $values['phase'] = $phase;
  1747. }
  1748. $success = chado_insert_record('featureloc', $values);
  1749. if (!$success) {
  1750. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Failed to insert featureloc", array());
  1751. exit;
  1752. return 0;
  1753. }
  1754. }
  1755. return 1;
  1756. }
  1757. /**
  1758. * Load a preoprty (featurepop) for the feature
  1759. *
  1760. * @param $feature
  1761. * @param $property
  1762. * @param $value
  1763. *
  1764. * @ingroup gff3_loader
  1765. */
  1766. function tripal_feature_load_gff3_property($feature, $property, $value) {
  1767. // first make sure the cvterm exists. if not, then add it
  1768. $select = array(
  1769. 'name' => $property,
  1770. 'cv_id' => array(
  1771. 'name' => 'feature_property',
  1772. ),
  1773. );
  1774. $result = chado_select_record('cvterm', array('*'), $select);
  1775. // if we don't have a property like this already, then add it otherwise, just return
  1776. if (count($result) == 0) {
  1777. $term = array(
  1778. 'id' => "null:$property",
  1779. 'name' => $property,
  1780. 'namespace' => 'feature_property',
  1781. 'is_obsolete' => 0,
  1782. 'cv_name' => 'feature_property',
  1783. 'is_relationship' => FALSE
  1784. );
  1785. $cvterm = (object) tripal_insert_cvterm($term, array('update_existing' => FALSE));
  1786. if (!$cvterm) {
  1787. tripal_report_error("tripal_feature", TRIPAL_WARNING, "Cannot add cvterm, $property", array());
  1788. return 0;
  1789. }
  1790. }
  1791. else {
  1792. $cvterm = $result[0];
  1793. }
  1794. // check to see if the property already exists for this feature
  1795. // if it does but the value is unique then increment the rank and add it.
  1796. // if the value is not unique then don't add it.
  1797. $add = 1;
  1798. $rank = 0;
  1799. $select = array(
  1800. 'feature_id' => $feature->feature_id,
  1801. 'type_id' => $cvterm->cvterm_id,
  1802. );
  1803. $options = array(
  1804. 'order_by' => array(
  1805. 'rank' => 'ASC',
  1806. ),
  1807. );
  1808. $results = chado_select_record('featureprop', array('*'), $select, $options);
  1809. foreach ($results as $prop) {
  1810. if (strcmp($prop->value, $value)==0) {
  1811. $add = NULL; // don't add it, it already exists
  1812. }
  1813. $rank = $prop->rank + 1;
  1814. }
  1815. // add the property if we pass the check above
  1816. if ($add) {
  1817. $values = array(
  1818. 'feature_id' => $feature->feature_id,
  1819. 'type_id' => $cvterm->cvterm_id,
  1820. 'value' => $value,
  1821. 'rank' => $rank,
  1822. );
  1823. $result = chado_insert_record('featureprop', $values);
  1824. if (!$result) {
  1825. tripal_report_error("tripal_feature", TRIPAL_WARNING, "cannot add featureprop, $property", array());
  1826. }
  1827. }
  1828. }
  1829. /**
  1830. * Load the FASTA sequences at the bottom of a GFF3 file
  1831. *
  1832. * @param $fh
  1833. * @param $interval
  1834. * @param $num_read
  1835. * @param $intv_read
  1836. * @param $line_num
  1837. * @param $filesize
  1838. * @param $job
  1839. *
  1840. * @ingroup gff3_loader
  1841. */
  1842. function tripal_feature_load_gff3_fasta($fh, $interval, &$num_read, &$intv_read, &$line_num, $filesize, $job) {
  1843. print "\nLoading FASTA sequences\n";
  1844. $residues = '';
  1845. $id = NULL;
  1846. $percent = sprintf("%.2f", ($num_read / $filesize) * 100);
  1847. print "Parsing Line $line_num (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  1848. // iterate through the remaining lines of the file
  1849. while ($line = fgets($fh)) {
  1850. $line_num++;
  1851. $size = drupal_strlen($line);
  1852. $num_read += $size;
  1853. $intv_read += $size;
  1854. $line = trim($line);
  1855. // update the job status every 1% features
  1856. if ($job and $intv_read >= $interval) {
  1857. $intv_read = 0;
  1858. $percent = sprintf("%.2f", ($num_read / $filesize) * 100);
  1859. print "Parsing Line $line_num (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  1860. tripal_set_job_progress($job, intval(($num_read / $filesize) * 100));
  1861. }
  1862. // if we encounter a definition line then get the name, uniquename,
  1863. // accession and relationship subject from the definition line
  1864. if (preg_match('/^>/', $line)) {
  1865. // if we are beginning a new sequence then save to the database the last one we just finished.
  1866. if ($id) {
  1867. $values = array('uniquename' => $id);
  1868. $result = chado_select_record('tripal_gff_temp', array('*'), $values);
  1869. if (count($result) == 0) {
  1870. tripal_report_error('tripal_feature', TRIPAL_WARNING, 'Cannot find feature to assign FASTA sequence: %uname',
  1871. array('%uname' => $id));
  1872. }
  1873. else {
  1874. // if we have a feature then add the residues
  1875. $feature = $result[0];
  1876. $values = array('residues' => $residues);
  1877. $match = array('feature_id' => $feature->feature_id);
  1878. chado_update_record('feature', $match, $values);
  1879. }
  1880. }
  1881. // get the feature ID for this ID from the tripal_gff_temp table
  1882. $id = preg_replace('/^>(.*)$/', '\1', $line);
  1883. $residues = '';
  1884. }
  1885. else {
  1886. $residues .= trim($line);
  1887. }
  1888. }
  1889. // add in the last sequence
  1890. $values = array('uniquename' => $id);
  1891. $result = chado_select_record('tripal_gff_temp', array('*'), $values);
  1892. if (count($result) == 0) {
  1893. tripal_report_error('tripal_feature', TRIPAL_WARNING, 'Cannot find feature to assign FASTA sequence: %uname',
  1894. array('%uname' => $id));
  1895. }
  1896. else {
  1897. // if we have a feature then add the residues
  1898. $feature = $result[0];
  1899. $values = array('residues' => $residues);
  1900. $match = array('feature_id' => $feature->feature_id);
  1901. chado_update_record('feature', $match, $values);
  1902. }
  1903. }
  1904. /**
  1905. * Load the target attribute of a gff3 record
  1906. *
  1907. * @param $feature
  1908. * @param $tags
  1909. * @param $target_organism_id
  1910. * @param $target_type
  1911. * @param $create_target
  1912. * @param $attr_locgroup
  1913. *
  1914. * @ingroup gff3_loader
  1915. */
  1916. function tripal_feature_load_gff3_target($feature, $tags, $target_organism_id, $target_type, $create_target, $attr_locgroup) {
  1917. // format is: "target_id start end [strand]", where strand is optional and may be "+" or "-"
  1918. $matched = preg_match('/^(.*?)\s+(\d+)\s+(\d+)(\s+[\+|\-])*$/', trim($tags['Target'][0]), $matches);
  1919. // the organism and type of the target may also be specified as an attribute. If so, then get that
  1920. // information
  1921. $gff_target_organism = array_key_exists('target_organism', $tags) ? $tags['target_organism'][0] : '';
  1922. $gff_target_type = array_key_exists('target_type', $tags) ? $tags['target_type'][0] : '';
  1923. // if we have matches and the Target is in the correct format then load the alignment
  1924. if ($matched) {
  1925. $target_feature = $matches[1];
  1926. $start = $matches[2];
  1927. $end = $matches[3];
  1928. // if we have an optional strand, convert it to a numeric value.
  1929. if ($matches[4]) {
  1930. if (preg_match('/^\+$/', trim($matches[4]))) {
  1931. $target_strand = 1;
  1932. }
  1933. elseif (preg_match('/^\-$/', trim($matches[4]))) {
  1934. $target_strand = -1;
  1935. }
  1936. else {
  1937. $target_strand = 0;
  1938. }
  1939. }
  1940. else {
  1941. $target_strand = 0;
  1942. }
  1943. $target_fmin = $start - 1;
  1944. $target_fmax = $end;
  1945. if ($end < $start) {
  1946. $target_fmin = $end - 1;
  1947. $target_fmax = $start;
  1948. }
  1949. // default the target organism to be the value passed into the function, but if the GFF
  1950. // file species the target organism then use that instead.
  1951. $t_organism_id = $target_organism_id;
  1952. if ($gff_target_organism) {
  1953. // get the genus and species
  1954. $success = preg_match('/^(.*?):(.*?)$/', $gff_target_organism, $matches);
  1955. if ($success) {
  1956. $values = array(
  1957. 'genus' => $matches[1],
  1958. 'species' => $matches[2],
  1959. );
  1960. $torganism = chado_select_record('organism', array('organism_id'), $values);
  1961. if (count($torganism) == 1) {
  1962. $t_organism_id = $torganism[0]->organism_id;
  1963. }
  1964. else {
  1965. tripal_report_error('tripal_feature', TRIPAL_WARNING, "Cannot find organism for target %target.",
  1966. array('%target' => $gff_target_organism));
  1967. $t_organism_id = '';
  1968. }
  1969. }
  1970. else {
  1971. tripal_report_error('tripal_feature', TRIPAL_WARNING, "The target_organism attribute is improperly formatted: %target.
  1972. It should be target_organism=genus:species.",
  1973. array('%target' => $gff_target_organism));
  1974. $t_organism_id = '';
  1975. }
  1976. }
  1977. // default the target type to be the value passed into the function, but if the GFF file
  1978. // species the target type then use that instead
  1979. $t_type_id = '';
  1980. if ($target_type) {
  1981. $values = array(
  1982. 'name' => $target_type,
  1983. 'cv_id' => array(
  1984. 'name' => 'sequence',
  1985. )
  1986. );
  1987. $type = chado_select_record('cvterm', array('cvterm_id'), $values);
  1988. if (count($type) == 1) {
  1989. $t_type_id = $type[0]->cvterm_id;
  1990. }
  1991. else {
  1992. tripal_report_error('tripal_feature', TRIPAL_ERROR, "The target type does not exist in the sequence ontology: %type. ",
  1993. array('%type' => $target_type));
  1994. exit;
  1995. }
  1996. }
  1997. if ($gff_target_type) {
  1998. $values = array(
  1999. 'name' => $gff_target_type,
  2000. 'cv_id' => array(
  2001. 'name' => 'sequence',
  2002. )
  2003. );
  2004. // get the cvterm_id for the target type
  2005. $type = chado_select_record('cvterm', array('cvterm_id'), $values);
  2006. if (count($type) == 1) {
  2007. $t_type_id = $type[0]->cvterm_id;
  2008. }
  2009. else {
  2010. // check to see if this is a synonym
  2011. $sql = "
  2012. SELECT CVTS.cvterm_id
  2013. FROM {cvtermsynonym} CVTS
  2014. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = CVTS.cvterm_id
  2015. INNER JOIN {cv} CV ON CV.cv_id = CVT.cv_id
  2016. WHERE CV.name = 'sequence' and CVTS.synonym = :synonym
  2017. ";
  2018. $synonym = chado_query($sql, array(':synonym' => $gff_target_type))->fetchObject();
  2019. if ($synonym) {
  2020. $t_type_id = $synonym->cvterm_id;
  2021. }
  2022. else {
  2023. tripal_report_error('tripal_feature', TRIPAL_WARNING, "The target_type attribute does not exist in the sequence ontology: %type. ",
  2024. array('%type' => $gff_target_type));
  2025. $t_type_id = '';
  2026. }
  2027. }
  2028. }
  2029. // we want to add a featureloc record that uses the target feature as the srcfeature (landmark)
  2030. // and the landmark as the feature.
  2031. tripal_feature_load_gff3_featureloc($feature, $organism, $target_feature, $target_fmin,
  2032. $target_fmax, $target_strand, $phase, $attr_fmin_partial, $attr_fmax_partial, $attr_residue_info,
  2033. $attr_locgroup, $t_type_id, $t_organism_id, $create_target, TRUE);
  2034. }
  2035. // the target attribute is not correctly formatted
  2036. else {
  2037. tripal_report_error('tripal_feature', TRIPAL_ERROR, "Could not add 'Target' alignment as it is improperly formatted: '%target'",
  2038. array('%target' => $tags['Target'][0]));
  2039. }
  2040. }