tripal_chado.phylotree.api.inc 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. <?php
  2. /**
  3. * @file
  4. * Provides API functions specificially for managing phylogenetic and taxonomic
  5. * tree records in Chado.
  6. */
  7. /**
  8. * @defgroup tripal_phylotree_api Chado Phylotree
  9. * @ingroup tripal_chado_api
  10. * @{
  11. * Provides API functions specificially for managing phylogenetic and taxonomic
  12. * tree records in Chado. The API consists of functions for creation,
  13. * retrieval, update and deltion (CRUD) for phylogenetic tree records as
  14. * well as importing of trees in the newick file format.
  15. * @}
  16. */
  17. /**
  18. * Validates an $options array for insert or update of a phylotree record.
  19. *
  20. * If validation passes then any values that needed validation lookups
  21. * (such as the dbxref, analysis, leaf_type, etc) will have their approriate
  22. * primary_keys added to the $options array, and missing default values
  23. * will also be added.
  24. *
  25. * @param $val_type
  26. * The type of validation. Can be either 'insert' or 'update'.
  27. * @param $options
  28. * An array of key/value pairs containing any of the valid keys for
  29. * either the chado_insert_phylotree() or chado_update_phylotree()
  30. * functions.
  31. * @param $errors
  32. * An empty array where validation error messages will be set. The keys
  33. * of the array will be name of the field from the options array and the
  34. * value is the error message.
  35. * @param $warnings
  36. * An empty array where validation warning messagges will be set. The
  37. * warnings should not stop an insert or an update but should be provided
  38. * to the user as information by a drupal_set_message() if appropriate. The
  39. * keys of the array will be name of the field from the options array and the
  40. * value is the error message.
  41. * @return
  42. * If validation failes then FALSE is returned. Any options that do not pass
  43. * validation checks will be added in the $errors array with the key being
  44. * the option and the value being the error message. If validation
  45. * is successful then TRUE is returned.
  46. *
  47. * @ingroup tripal_phylotree_api
  48. */
  49. function chado_validate_phylotree($val_type, &$options, &$errors, &$warnings) {
  50. if ($val_type != 'insert' and $val_type != 'update') {
  51. tripal_report_error('tripal_phylogeny', TRIPAL_ERROR, "The $val_type argument must be either 'update or 'insert'.");
  52. }
  53. // Set Defaults.
  54. if ($val_type == 'insert') {
  55. // Match by feature name.
  56. if (!array_key_exists('match', $options)) {
  57. $options['match'] = 'name';
  58. }
  59. // The regular expression is to match the entire node name.
  60. if (!array_key_exists('name_re', $options)) {
  61. $options['name_re'] = '^(.*)$';
  62. }
  63. // A dbxref is not required by Tripal but is required by the database
  64. // field in the phylotree table. Therefore, if the dbxref is not provided
  65. // we can set this to be the null database and null dbxref which
  66. // is represented as 'null:local:null'
  67. if (!array_key_exists('dbxref', $options)) {
  68. $options['dbxref'] = "null:local:null";
  69. }
  70. }
  71. // Make sure required values are set.
  72. if ($val_type == 'insert') {
  73. if (!array_key_exists('name', $options)) {
  74. $errors['name'] = t('Please provide the name of the tree.');
  75. return FALSE;
  76. }
  77. if (!array_key_exists('description', $options)) {
  78. $errors['description'] = t('Please provide a description for this tree.');
  79. return FALSE;
  80. }
  81. if (!array_key_exists('format', $options) or !$options['format']) {
  82. $errors['format'] = t('Please provide a file format for the tree file.');
  83. return FALSE;
  84. }
  85. // Make sure the file format is correct.
  86. if ($options['format'] != 'newick' and $options['format'] != 'taxonomy') {
  87. $errors['format'] = t('The file format is not supported. Currently only the "newick" file format is supported.');
  88. return FALSE;
  89. }
  90. }
  91. else {
  92. // Does the phylotree ID exist and is it valid.
  93. if (!array_key_exists('phylotree_id', $options)) {
  94. $errors['phylotree_id'] = t('Please provide the ID for the tree.');
  95. return FALSE;
  96. }
  97. $exists = chado_select_record('phylotree', array('phylotree_id'),
  98. array('phylotree_id' => $options['phylotree_id']), array('has_record' => 1));
  99. if (!$exists) {
  100. $errors['phylotree_id'] = t('The phylotree_id does not exist.');
  101. return FALSE;
  102. }
  103. }
  104. // Make sure the file exists if one is specified.
  105. if (array_key_exists('tree_file', $options) and $options['tree_file']) {
  106. // If this is a numeric Drupal file then all is good, no need to check.
  107. if (!is_numeric($options['tree_file'])) {
  108. if (!file_exists($options['tree_file'])) {
  109. $errors['tree_file'] = t('The file provided does not exists.');
  110. return FALSE;
  111. }
  112. }
  113. // Make sure the file format is correct.
  114. if (!array_key_exists('format', $options) or
  115. ($options['format'] != 'newick' and $options['format'] != 'taxonomy')) {
  116. $errors['format'] = t('Please provide a supported file format. Currently only the "newick" file format is supported.');
  117. return FALSE;
  118. }
  119. // If no leaf type is provided then use the polypeptide term.
  120. if (!array_key_exists('leaf_type', $options) or !$options['leaf_type']) {
  121. $options['leaf_type'] = 'polypeptide';
  122. }
  123. }
  124. // Make sure the analysis exists.
  125. $analysis = NULL;
  126. if (array_key_exists('analysis_id', $options) and $options['analysis_id']) {
  127. $analysis = chado_select_record('analysis', array('analysis_id'), array('analysis_id' => $options['analysis_id']));
  128. if (!$analysis) {
  129. $errors['analysis_id'] = t('The analysis name provided does not exist.');
  130. return FALSE;
  131. }
  132. $options['analysis_id'] = $analysis[0]->analysis_id;
  133. }
  134. if (array_key_exists('analysis', $options) and $options['analysis']) {
  135. $analysis = chado_select_record('analysis', array('analysis_id'), array('name' => $options['analysis']));
  136. if (!$analysis) {
  137. $errors['analysis'] = t('The analysis ID provided does not exist.');
  138. return FALSE;
  139. }
  140. $options['analysis_id'] = $analysis[0]->analysis_id;
  141. }
  142. // Make sure the leaf type exists.
  143. $type = NULL;
  144. if (array_key_exists('leaf_type', $options) and $options['leaf_type']) {
  145. if ($options['leaf_type'] == 'taxonomy') {
  146. $values = array(
  147. 'cv_id' => array(
  148. 'name' => 'EDAM'
  149. ),
  150. 'name' => 'Species tree'
  151. );
  152. $type = chado_select_record('cvterm', array('cvterm_id'), $values);
  153. }
  154. else {
  155. $values = array(
  156. 'cv_id' => array(
  157. 'name' => 'sequence'
  158. ),
  159. 'name' => $options['leaf_type']
  160. );
  161. $type = chado_select_record('cvterm', array('cvterm_id'), $values);
  162. if (!$type) {
  163. $errors['leaf_type'] = t('The leaf_type provided is not a valid Sequence Ontology term: %term.');
  164. return FALSE;
  165. }
  166. }
  167. $options['type_id'] = $type[0]->cvterm_id;
  168. }
  169. // A Dbxref is required by the phylotree module, but if the
  170. // tree was generated in-house and the site admin doens't want to
  171. // assign a local dbxref then we will set it to the null db
  172. // and the local:null dbxref.
  173. if (array_key_exists('dbxref', $options)) {
  174. if (!$options['dbxref']) {
  175. $options['dbxref'] = 'null:local:null';
  176. }
  177. $matches = array();
  178. preg_match('/^(.*?):(.*)$/', $options['dbxref'], $matches);
  179. $db_name = $matches[1];
  180. $accession = $matches[2];
  181. $values = array(
  182. 'accession' => $accession,
  183. 'db_id' => array(
  184. 'name' => $db_name
  185. ),
  186. );
  187. $dbxref = chado_generate_var('dbxref', $values);
  188. if (!$dbxref) {
  189. $db = chado_generate_var('db', array( 'name' => $db_name));
  190. if (!$db){
  191. $errors['dbxref'] = t('
  192. dbxref could not be created for db: %dbxref.', array('%dbxref' => $dbxref));
  193. return FALSE;
  194. }
  195. $dbxref = chado_insert_record('dbxref', $values);
  196. if (!$dbxref){
  197. $errors['dbxref'] = t('
  198. dbxref could not be created for db: %dbxref.', array('%dbxref' => $dbxref));
  199. return FALSE;
  200. }
  201. }
  202. if (is_array($dbxref)){
  203. $options['dbxref_id'] = $dbxref['dbxref_id'];
  204. }else {
  205. $options['dbxref_id'] = $dbxref->dbxref_id;
  206. }
  207. }
  208. // Make sure the tree name is unique.
  209. if (array_key_exists('name', $options) and $options['name']) {
  210. $sql = "
  211. SELECT *
  212. FROM {phylotree} P
  213. WHERE
  214. P.name = :name
  215. ";
  216. $args = array(':name' => $options['name']);
  217. if ($val_type == 'update') {
  218. $sql .= " AND NOT P.phylotree_id = :phylotree_id";
  219. $args[':phylotree_id'] = $options['phylotree_id'];
  220. }
  221. $result = chado_query($sql, $args)->fetchObject();
  222. if ($result) {
  223. $errors['name'] = t("The tree name is in use by another tree. Please provide a different unique name for this tree.");
  224. }
  225. }
  226. return TRUE;
  227. }
  228. /**
  229. * Inserts a phylotree record into Chado.
  230. *
  231. * This function validates the options passed prior to insertion of the record,
  232. * and if validation passes then any values in the options array that needed
  233. * validation lookups (such as the dbxref, analysis, leaf_type, etc) will have
  234. * their approriate primary key values added to the options array.
  235. *
  236. * @param $options
  237. * An array of key value pairs with the following keys required:
  238. * 'name': The name of the tree. This will be displayed to users.
  239. * 'description: A description about the tree
  240. * 'anlaysis_id: The ID of the analysis to which this phylotree should be
  241. * associated.
  242. * 'analysis': If the analysis_id key is not used then the analysis name
  243. * may be provided to identify the analysis to which the tree
  244. * should be associated.
  245. * 'leaf_type': A sequence ontology term or the word 'organism'. If the
  246. * type is 'organism' then this tree represents a
  247. * taxonomic tree. The default, if not specified, is the
  248. * term 'polypeptide'.
  249. * 'tree_file': The path of the file containing the phylogenetic tree to
  250. * import or a Drupal managed_file numeric ID.
  251. * 'format': The file format. Currently only 'newick is supported'.
  252. *
  253. * Optional keys:
  254. * 'dbxref': A database cross-reference of the form DB:ACCESSION.
  255. * Where DB is the database name, which is already present
  256. * in Chado, and ACCESSION is the unique identifier for
  257. * this tree in the remote database.
  258. * 'name_re': If the leaf type is NOT 'taxonomy', then the value of
  259. * this field can be a regular expression to pull out
  260. * the name of the feature from the node label in the
  261. * intput tree. If no value is provided the entire label is
  262. * used.
  263. * 'match': Set to 'uniquename' if the leaf nodes should be matched
  264. * with the feature uniquename.
  265. * 'load_now': If set, the tree will be loaded immediately if a tree_file
  266. * is provided. Otherwise, the tree will be loaded via
  267. * a Tripal jobs call.
  268. * 'no_load': If set the tree file will not be loaded.
  269. * @param $errors
  270. * An empty array where validation error messages will be set. The keys
  271. * of the array will be name of the field from the options array and the
  272. * value is the error message.
  273. * @param $warnings
  274. * An empty array where validation warning messagges will be set. The
  275. * warnings should not stop an insert or an update but should be provided
  276. * to the user as information by a drupal_set_message() if appropriate. The
  277. * keys of the array will be name of the field from the options array and the
  278. * value is the error message.
  279. * @return
  280. * TRUE for success and FALSE for failure.
  281. *
  282. * @ingroup tripal_phylotree_api
  283. */
  284. function chado_insert_phylotree(&$options, &$errors, &$warnings) {
  285. global $user;
  286. $options['name_re'] = $options['name_re'] ? trim($options['name_re']) : NULL;
  287. $options['leaf_type'] = trim($options['leaf_type']);
  288. $options['name'] = trim($options['name']);
  289. $options['format'] = trim($options['format']);
  290. $options['tree_file'] = trim($options['tree_file']);
  291. $options['analysis_id'] = $options['analysis_id'] ? $options['analysis_id'] : NULL;
  292. // Validate the incoming options.
  293. $success = chado_validate_phylotree('insert', $options, $errors, $warnings);
  294. if (!$success) {
  295. foreach ($errors as $field => $message) {
  296. tripal_report_error('tripal_phylogeny', TRIPAL_ERROR, $message);
  297. }
  298. return FALSE;
  299. }
  300. // If we're here then all is good, so add the phylotree record.
  301. $values = array(
  302. 'analysis_id' => $options['analysis_id'],
  303. 'name' => $options['name'],
  304. 'dbxref_id' => $options['dbxref_id'],
  305. 'comment' => $options['description'],
  306. 'type_id' => $options['type_id'],
  307. );
  308. $phylotree = chado_insert_record('phylotree', $values);
  309. if (!$phylotree) {
  310. drupal_set_message(t('Unable to add phylotree.'), 'warning');
  311. tripal_report_error('tripal_phylogeny', TRIPAL_WARNING, 'Insert phylotree: Unable to create phylotree where values: %values',
  312. array('%values' => print_r($values, TRUE)));
  313. return FALSE;
  314. }
  315. $phylotree_id = $phylotree['phylotree_id'];
  316. $options['phylotree_id'] = $phylotree_id;
  317. // If the tree_file is numeric then it is a Drupal managed file and
  318. // we want to make the file permanent and associated with the tree.
  319. if (is_numeric($options['tree_file'])) {
  320. $file = NULL;
  321. $file = file_load($options['tree_file']);
  322. $file->status = FILE_STATUS_PERMANENT;
  323. $file = file_save($file);
  324. file_usage_add($file, 'tripal_phylogeny', $options['format'], $phylotree_id);
  325. $real_file_path = drupal_realpath($file->uri);
  326. }
  327. else {
  328. $real_file_path = $options['tree_file'];
  329. }
  330. // If caller has requested to load the file now then do so, otherwise
  331. // submit using a Tripal job.
  332. if (!array_key_exists('no_load', $options) or !$options['no_load']) {
  333. if (array_key_exists('load_now', $options) and $options['load_now']) {
  334. $args = array(
  335. 'phylotree_id' => $phylotree_id,
  336. 'leaf_type' => $options['leaf_type'],
  337. 'match' => $options['match'] ? 'uniquename' : 'name',
  338. 'name_re' => $options['name_re'],
  339. );
  340. chado_phylogeny_import_tree_file($real_file_path, $options['format'], $args);
  341. }
  342. else {
  343. $args = array(
  344. $real_file_path,
  345. 'newick',
  346. array(
  347. 'phylotree_id' => $phylotree_id,
  348. 'leaf_type' => $options['leaf_type'],
  349. 'match' => $options['match'] ? 'uniquename' : 'name',
  350. 'name_re' => $options['name_re'],
  351. ),
  352. );
  353. if (tripal_add_job("Import Tree File: " . $file->filename, 'tripal_phylogeny',
  354. 'chado_phylogeny_import_tree_file', $args, $user->uid)) {
  355. drupal_set_message(t('The tree visualizations will appear once the tree is fully imported.'));
  356. }
  357. }
  358. }
  359. return TRUE;
  360. }
  361. /**
  362. * Updates a phylotree record into Chado.
  363. *
  364. * This function validates the options passed prior to update of the record
  365. * and if validation passes then any values in the options array that needed
  366. * validation lookups (such as the dbxref, analysis, leaf_type, etc) will have
  367. * their approriate primary key values added to the options array. A Drupal
  368. * File object will be added to the options array for the tree file if one
  369. * is provided.
  370. *
  371. *
  372. * @param $phylotree_id
  373. * The ID of the phylotree to update.
  374. * @param $options
  375. * An array of key value pairs with the following optional keys:
  376. * 'name': The name of the tree. This will be displayed to users.
  377. * 'description: A description about the tree
  378. * 'anlaysis_id: The ID of the analysis to which this phylotree should be
  379. * associated.
  380. * 'analysis': If the analysis_id key is not used then the analysis name
  381. * may be provided to identify the analysis to which the tree
  382. * should be associated.
  383. * 'leaf_type': A sequence ontology term or the word 'organism'. If the
  384. * type is 'organism' then this tree represents a
  385. * taxonomic tree. The default, if not specified, is the
  386. * term 'polypeptide'.
  387. * 'tree_file': The path of the file containing the phylogenetic tree to
  388. * import or a Drupal managed_file numeric ID.
  389. * 'format': The file format. Currently only 'newick is supported'
  390. * 'dbxref': A database cross-reference of the form DB:ACCESSION.
  391. * Where DB is the database name, which is already present
  392. * in Chado, and ACCESSION is the unique identifier for
  393. * this tree in the remote database.
  394. * 'name_re': If the leaf type is NOT 'taxonomy', then the value of
  395. * this field can be a regular expression to pull out
  396. * the name of the feature from the node label in the
  397. * intput tree. If no value is provided the entire label is
  398. * used.
  399. * 'match': Set to 'uniquename' if the leaf nodes should be matched
  400. * with the feature uniquename.
  401. * 'load_now': If set, the tree will be loaded immediately if a tree_file
  402. * is provided. Otherwise, the tree will be loaded via
  403. * a Tripal jobs call.
  404. *
  405. * @ingroup tripal_phylotree_api
  406. */
  407. function chado_update_phylotree($phylotree_id, &$options) {
  408. global $user;
  409. // Validate the incoming options.
  410. $errors = array();
  411. $warnings = array();
  412. $success = chado_validate_phylotree('update', $options, $errors, $warnings);
  413. if (!$success) {
  414. foreach ($errors as $field => $message) {
  415. tripal_report_error('tripal_phylogeny', TRIPAL_ERROR, $message);
  416. }
  417. return FALSE;
  418. }
  419. // If we're here then all is good, so update the phylotree record.
  420. $match = array(
  421. 'phylotree_id' => $phylotree_id,
  422. );
  423. if (array_key_exists('name', $options) and $options['name']) {
  424. $values['name'] = $options['name'];
  425. }
  426. if (array_key_exists('analysis_id', $options) and $options['analysis_id']) {
  427. $values['analysis_id'] = $options['analysis_id'];
  428. }
  429. if (array_key_exists('dbxref_id', $options) and $options['dbxref_id']) {
  430. $values['dbxref_id'] = $options['dbxref_id'];
  431. }
  432. if (array_key_exists('description', $options) and $options['description']) {
  433. $values['comment'] = $options['description'];
  434. }
  435. if (array_key_exists('type_id', $options) and $options['type_id']) {
  436. $values['type_id'] = $options['type_id'];
  437. }
  438. $phylotree = chado_update_record('phylotree', $match, $values, array('return_record' => TRUE));
  439. if (!$phylotree) {
  440. drupal_set_message(t('Unable to update phylotree.'), 'warning');
  441. tripal_report_error('tripal_phylogeny', TRIPAL_WARNING,
  442. 'Update phylotree: Unable to update phylotree where values: %values',
  443. array('%values' => print_r($values, TRUE))
  444. );
  445. }
  446. // If we have a tree file, then import the tree.
  447. if (array_key_exists('tree_file', $options) and $options['tree_file']) {
  448. // Remove any existing nodes
  449. chado_delete_record('phylonode', array('phylotree_id' => $options['phylotree_id']));
  450. // Make sure if we already have a file that we remove the old one.
  451. $sql = "
  452. SELECT FM.fid
  453. FROM {file_managed} FM
  454. INNER JOIN {file_usage} FU on FM.fid = FU.fid
  455. WHERE FU.id = :id and FU.module = 'tripal_phylogeny'
  456. ";
  457. $fid = db_query($sql, array(':id' => $options['phylotree_id']))->fetchField();
  458. if ($fid) {
  459. $file = file_load($fid);
  460. file_delete($file, TRUE);
  461. }
  462. // If the tree_file is numeric then it is a Drupal managed file and
  463. // we want to make the file permanent and associated with the tree.
  464. if (is_numeric($options['tree_file'])) {
  465. $file = file_load($options['tree_file']);
  466. $file->status = FILE_STATUS_PERMANENT;
  467. $file = file_save($file);
  468. file_usage_add($file, 'tripal_phylogeny', 'newick', $options['phylotree_id']);
  469. // Add a job to parse the new node tree.
  470. $real_file_path = drupal_realpath($file->uri);
  471. }
  472. else {
  473. $real_file_path = $options['tree_file'];
  474. }
  475. // If caller has requested to load the file now then do so, otherwise
  476. // submit using a Tripal job.
  477. if (array_key_exists('load_now', $options) and $options['load_now']) {
  478. $args = array(
  479. 'phylotree_id' => $options['phylotree_id'],
  480. 'leaf_type' => $options['leaf_type'],
  481. 'match' => $options['match'] ? 'uniquename' : 'name',
  482. 'name_re' => $options['name_re'],
  483. );
  484. chado_phylogeny_import_tree_file($real_file_path, $options['format'], $args);
  485. }
  486. else {
  487. $args = array(
  488. $real_file_path,
  489. 'newick',
  490. array(
  491. 'phylotree_id' => $options['phylotree_id'],
  492. 'leaf_type' => $options['leaf_type'],
  493. 'match' => $options['match'] ? 'uniquename' : 'name',
  494. 'name_re' => $options['name_re'],
  495. ),
  496. );
  497. if (tripal_add_job("Import Tree File: " . $file->filename, 'tripal_phylogeny',
  498. 'chado_phylogeny_import_tree_file', $args, $user->uid)) {
  499. drupal_set_message(t('The tree visualizations will appear once the tree is fully imported.'));
  500. }
  501. }
  502. }
  503. return TRUE;
  504. }
  505. /**
  506. * Deletes a phylotree record from Chado.
  507. *
  508. * @param $phylotree_id
  509. *
  510. * @return
  511. * TRUE on success, FALSE on failure.
  512. *
  513. * @ingroup tripal_phylotree_api
  514. */
  515. function chado_delete_phylotree($phylotree_id) {
  516. // If we don't have a phylotree id for this node then this isn't a node of
  517. // type chado_phylotree or the entry in the chado_phylotree table was lost.
  518. if (!$phylotree_id) {
  519. tripal_report_error('tripal_phylogeny', TRIPAL_ERROR,
  520. 'Please provide a phylotree_id to delete a tree.');
  521. return FALSE;
  522. }
  523. // Remove the tree
  524. $values = array('phylotree_id' => $phylotree_id);
  525. return chado_delete_record('phylotree', $values);
  526. }
  527. /**
  528. * Iterates through the tree and sets the left and right indicies.
  529. *
  530. * @param $tree
  531. * The tree array.
  532. * @param $index
  533. * This parameters is not used when the function is first called. It
  534. * is used for recursive calls.
  535. *
  536. * @ingroup tripal_phylotree_api
  537. */
  538. function chado_assign_phylogeny_tree_indices(&$tree, &$index = 1) {
  539. // Assign a left and right index to each node. The child node must
  540. // have a right and left index less than that of it's parents. We
  541. // increment the index by 100 to give space for new nodes that might
  542. // be added later.
  543. if (array_key_exists('name', $tree)) {
  544. $tree['left_index'] = $index += 100;
  545. if (array_key_exists('is_leaf', $tree)) {
  546. $tree['right_index'] = $index += 100;
  547. }
  548. }
  549. if (array_key_exists('branch_set', $tree)) {
  550. foreach ($tree['branch_set'] as $key => $node) {
  551. chado_assign_phylogeny_tree_indices($tree['branch_set'][$key], $index);
  552. $tree['right_index'] = $index += 100;
  553. }
  554. }
  555. }
  556. /**
  557. * Iterates through the tree array and creates phylonodes in Chado.
  558. *
  559. * The function iterates through the tree in a top-down approach adding
  560. * parent internal nodes prior to leaf nodes. Each node of the tree should have
  561. * the following fields:
  562. *
  563. * -name: The name (or label) for this node.
  564. * -depth: The depth of the node in the tree.
  565. * -is_root: Set to 1 if this node is a root node.
  566. * -is_leaf: Set to 1 if this node is a leaf node.
  567. * -is_internal: Set to 1 if this node is an internal node.
  568. * -left_index: The index of the node to the left in the tree.
  569. * -right_index: The index of the node to the right in the tree.
  570. * -branch_set: An array containing a list of nodes of that are children
  571. * of the node.
  572. * -parent: The name of the parent node.
  573. * -organism_id: The organism_id for associtating the node with an organism.
  574. * -properties: An array of key/value pairs where the key is the cvterm_id
  575. * and the value is the property value. These properties
  576. * will be assocaited with the phylonode.
  577. *
  578. * Prior to importing the tree the indicies can be set by using the
  579. * chado_assign_phylogeny_tree_indices() function.
  580. *
  581. * @param $tree
  582. * The tree array.
  583. * @param $phylotree.
  584. * The phylotree object (from Chado).
  585. * @param $options
  586. * The options provide some direction for how the tree is imported. The
  587. * following keys can be used:
  588. * -taxonomy: Set to 1 if this tree is a taxonomic tree. Set to 0
  589. * otherwise.
  590. * -leaf_type: Set to the leaf type name. If this is a non-taxonomic tree
  591. * that is associated with features, then this should be the
  592. * Sequence Ontology term for the feature (e.g. polypeptide).
  593. * If this is a taxonomic tree then this option is not needed.
  594. * -match: Set to either 'name' or 'uniquename'. This is used for
  595. * matching the feature name or uniquename with the node name.
  596. * This is not needed for taxonomic trees.
  597. * -match_re: Set to a regular that can be used for matching the node
  598. * name with the feature name if the node name is not
  599. * identical to the feature name.
  600. * @param $vocab
  601. * Optional. An array containing a set of key/value pairs that maps node
  602. * types to CV terms. The keys must be 'root', 'internal' or 'leaf'. If
  603. * no vocab is provded then the terms provided by the tripal_phylogeny
  604. * CV will be used.
  605. * @param $parent
  606. * This argument is not needed when the funtion is first called. This
  607. * function is recursive and this argument is used on recursive calls.
  608. *
  609. * @ingroup tripal_phylotree_api
  610. */
  611. function chado_phylogeny_import_tree(&$tree, $phylotree, $options, $vocab = array(), $parent = NULL) {
  612. // Get the vocabulary terms used to describe nodes in the tree if one
  613. // wasn't provided.
  614. if (count($vocab) == 0) {
  615. $vocab = chado_phylogeny_get_node_types_vocab();
  616. }
  617. if (is_array($tree) and array_key_exists('name', $tree)) {
  618. $values = array(
  619. 'phylotree_id' => $phylotree->phylotree_id,
  620. 'left_idx' => $tree['left_index'],
  621. 'right_idx' => $tree['right_index'],
  622. );
  623. // Add in any optional values to the $values array if they are present.
  624. if (!empty($tree['name']) and $tree['name'] != '') {
  625. $values['label'] = $tree['name'];
  626. }
  627. if (!empty($tree['length']) and $tree['length'] != '') {
  628. $values['distance'] = $tree['length'];
  629. }
  630. // Set the type of node.
  631. if ($tree['is_root']) {
  632. $values['type_id'] = $vocab['root']->cvterm_id;
  633. }
  634. else if ($tree['is_internal']) {
  635. $values['type_id'] = $vocab['internal']->cvterm_id;
  636. $values['parent_phylonode_id'] = $parent['phylonode_id'];
  637. // TOOD: a feature may be associated here but it is recommended that it
  638. // be a feature of type SO:match and should represent the alignment of
  639. // all features beneath it.
  640. }
  641. else if ($tree['is_leaf']) {
  642. $values['type_id'] = $vocab['leaf']->cvterm_id;
  643. $values['parent_phylonode_id'] = $parent['phylonode_id'];
  644. // Match this leaf node with an organism or feature depending on the
  645. // type of tree. But we can't do that if we don't have a name.
  646. if (!empty($tree['name']) and $tree['name'] != '') {
  647. if (!$options['taxonomy']) {
  648. // This is a sequence-based tree. Try to match leaf nodes with
  649. // features.
  650. // First, Get the Name and uniquename for the feature.
  651. $matches = array();
  652. $sel_values = array();
  653. if ($options['match'] == "name") {
  654. $sel_values['name'] = $tree['name'];
  655. $re = $options['name_re'];
  656. if (preg_match("/$re/", $tree['name'], $matches)) {
  657. $sel_values['name'] = $matches[1];
  658. }
  659. }
  660. else {
  661. $sel_values['uniquename'] = $tree['name'];
  662. $re = $options['name_re'];
  663. if (preg_match("/$re/", $tree['name'], $matches)) {
  664. $sel_values['uniquename'] = $matches[1];
  665. }
  666. }
  667. $sel_values['type_id'] = array(
  668. 'name' => $options['leaf_type'],
  669. 'cv_id' => array(
  670. 'name' => 'sequence'
  671. ),
  672. );
  673. $sel_columns = array('feature_id');
  674. $feature = chado_select_record('feature', $sel_columns, $sel_values);
  675. if (count($feature) > 1) {
  676. // Found multiple features, cannot make an association.
  677. }
  678. else if (count($feature) == 1) {
  679. $values['feature_id'] = $feature[0]->feature_id;
  680. }
  681. else {
  682. // Could not find a feature that matches the name or uniquename
  683. }
  684. }
  685. }
  686. }
  687. // Insert the new node and then add it's assigned phylonode_id to the node.
  688. $phylonode = chado_insert_record('phylonode', $values);
  689. $tree['phylonode_id'] = $phylonode['phylonode_id'];
  690. // This is a taxonomic tree, so assocaite this node with an
  691. // organism if one is provided.
  692. if (array_key_exists('organism_id', $tree)) {
  693. $values = array(
  694. 'phylonode_id' => $tree['phylonode_id'],
  695. 'organism_id' => $tree['organism_id']
  696. );
  697. $pylonode_organism = chado_insert_record('phylonode_organism', $values);
  698. }
  699. // Associate any properties.
  700. if (array_key_exists('properties', $tree)) {
  701. foreach ($tree['properties'] as $type_id => $value) {
  702. $values = array(
  703. 'phylonode_id' => $tree['phylonode_id'],
  704. 'type_id' => $type_id,
  705. 'value' => $value,
  706. );
  707. $pylonode_organism = chado_insert_record('phylonodeprop', $values);
  708. }
  709. }
  710. }
  711. if (is_array($tree) and array_key_exists('branch_set', $tree)) {
  712. foreach ($tree['branch_set'] as $key => $node) {
  713. chado_phylogeny_import_tree($tree['branch_set'][$key], $phylotree, $options, $vocab, $tree);
  714. }
  715. }
  716. }
  717. /**
  718. * Get the vocabulary terms used to describe nodes in the tree.
  719. *
  720. * @return
  721. * Array of vocab info or FALSE on failure.
  722. *
  723. * @ingroup tripal_phylotree_api
  724. */
  725. function chado_phylogeny_get_node_types_vocab() {
  726. // Get the vocabulary terms used to describe nodes in the tree.
  727. $values = array(
  728. 'name' => 'phylo_leaf',
  729. 'cv_id' => array(
  730. 'name' => 'tripal_phylogeny',
  731. ),
  732. );
  733. $leaf = chado_generate_var('cvterm', $values);
  734. if (!$leaf) {
  735. tripal_report_error('tripal_phylogeny', TRIPAL_ERROR,
  736. "Could not find the leaf vocabulary term: 'phylo_leaf'. It should " .
  737. "already be present as part of the tripal_phylogeny vocabulary.");
  738. return FALSE;
  739. }
  740. $values['name'] = 'phylo_interior';
  741. $internal = chado_generate_var('cvterm', $values);
  742. if (!$internal) {
  743. tripal_report_error('tripal_phylogeny', TRIPAL_ERROR,
  744. "Could not find the leaf vocabulary term: 'phylo_interior'. It should " .
  745. "already be present as part of the tripal_phylogeny vocabulary.");
  746. return FALSE;
  747. }
  748. $values['name'] = 'phylo_root';
  749. $root = chado_generate_var('cvterm', $values);
  750. if (!$root) {
  751. tripal_report_error('tripal_phylogeny', TRIPAL_ERROR,
  752. "Could not find the leaf vocabulary term: 'phylo_root'. It should " .
  753. "already be present as part of the tripal_phylogeny vocabulary.");
  754. return FALSE;
  755. }
  756. $vocab = array(
  757. 'leaf' => $leaf,
  758. 'internal' => $internal,
  759. 'root' => $root,
  760. );
  761. return $vocab;
  762. }
  763. /**
  764. * Imports a tree file.
  765. *
  766. * This function is used as a wrapper for loading a phylogenetic tree using
  767. * any number of file loaders.
  768. *
  769. * @param $file_name
  770. * The name of the file containing the phylogenetic tree to import.
  771. * @param $format
  772. * The format of the file. Currently only the 'newick' file format is
  773. * supported.
  774. * @param $options
  775. * Options if the phylotree record already exists:
  776. * 'phylotree_id': The imported nodes will be associated with this tree.
  777. * 'leaf_type': A sequence ontology term or the word 'organism'. If the
  778. * type is 'organism' then this tree represents a
  779. * taxonomic tree. The default, if not specified, is the
  780. * term 'polypeptide'.
  781. * 'name_re': If the leaf type is NOT 'taxonomy', then the value of
  782. * this field can be a regular expression to pull out
  783. * the name of the feature from the node label in the
  784. * intput tree. If no value is provided the entire label is
  785. * used.
  786. * 'match': Set to 'uniquename' if the leaf nodes should be matched
  787. * with the feature uniquename.
  788. *
  789. * @ingroup tripal_phylotree_api
  790. */
  791. function chado_phylogeny_import_tree_file($file_name, $format, $options = array(), $job_id = NULL) {
  792. // Set some option details.
  793. if (!array_key_exists('leaf_type', $options)) {
  794. $options['leaf_type'] = 'polypeptide';
  795. }
  796. if (!array_key_exists('match', $options)) {
  797. $options['match'] = 'name';
  798. }
  799. if (!array_key_exists('name_re', $options)) {
  800. $options['name_re'] = '^(.*)$';
  801. }
  802. $options['name_re'] = trim($options['name_re']);
  803. // If a phylotree ID is not passed in then make sure we have the other
  804. // required fields for creating a tree.
  805. if (!array_key_exists('phylotree_id', $options)) {
  806. if (!array_key_exists('name', $options)) {
  807. tripal_report_error('tripal_phylogeny', TRIPAL_ERROR,
  808. 'The phylotree_id is required for importing the tree.');
  809. return FALSE;
  810. }
  811. }
  812. // Get the phylotree record.
  813. $values = array('phylotree_id' => $options['phylotree_id']);
  814. $phylotree = chado_generate_var('phylotree', $values);
  815. if (!$phylotree) {
  816. tripal_report_error('tripal_phylogeny', TRIPAL_ERROR,
  817. 'Could not find the phylotree using the ID provided: %phylotree_id.',
  818. array('%phylotree_id' => $options['phylotree_id']));
  819. return FALSE;
  820. }
  821. $transaction = db_transaction();
  822. print "\nNOTE: Loading of this tree file is performed using a database transaction. \n" .
  823. "If the load fails or is terminated prematurely then the entire set of \n" .
  824. "insertions/updates is rolled back and will not be found in the database\n\n";
  825. try {
  826. // Parse the file according to the format indicated.
  827. if ($format == 'newick') {
  828. // Parse the tree into the expected nested node format.
  829. module_load_include('inc', 'tripal_chado', 'includes/loaders/tripal_chado.phylotree_newick');
  830. $tree = tripal_phylogeny_parse_newick_file($file_name);
  831. // Assign the right and left indecies to the tree ndoes.
  832. chado_assign_phylogeny_tree_indices($tree);
  833. }
  834. // Iterate through the tree nodes and add them to Chado in accordance
  835. // with the details in the $options array.
  836. chado_phylogeny_import_tree($tree, $phylotree, $options);
  837. }
  838. catch (Exception $e) {
  839. $transaction->rollback();
  840. watchdog_exception('tripal_phylogeny', $e);
  841. }
  842. }