tripal_chado.phylotree.api.inc 34 KB

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