tripal_feature.gff_loader.inc 85 KB

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