gff_loader.inc 55 KB

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