gff_loader.inc 72 KB

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