tripal_feature.gff_loader.inc 85 KB

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