GFF3Importer.inc 88 KB

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