gff_loader.inc 56 KB

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