gff_loader.inc 77 KB

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