GFF3Loader.inc 91 KB

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