tripal_feature.gff_loader.inc 77 KB

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