tripal_feature.fasta_loader.inc 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. <?php
  2. /**
  3. * @file
  4. * Provides fasta loading functionality. Creates features based on their specification
  5. * in a fasta file.
  6. */
  7. /**
  8. * @defgroup fasta_loader FASTA Feature Loader
  9. * @ingroup tripal_feature
  10. * @{
  11. * Provides fasta loading functionality. Creates features based on their specification
  12. * in a fasta file.
  13. * @}
  14. *
  15. */
  16. /**
  17. * The form to submit a fasta loading job
  18. *
  19. * @ingroup fasta_loader
  20. */
  21. function tripal_feature_fasta_load_form() {
  22. $form['fasta_file']= array(
  23. '#type' => 'textfield',
  24. '#title' => t('FASTA File'),
  25. '#description' => t('Please enter the full system path for the FASTA file, or a path within the Drupal
  26. installation (e.g. /sites/default/files/xyz.obo). The path must be accessible to the
  27. server on which this Drupal instance is running.'),
  28. '#required' => TRUE,
  29. );
  30. // get the list of organisms
  31. $sql = "SELECT * FROM {organism} ORDER BY genus, species";
  32. $org_rset = chado_query($sql);
  33. $organisms = array();
  34. $organisms[''] = '';
  35. while ($organism = $org_rset->fetchObject()) {
  36. $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
  37. }
  38. $form['organism_id'] = array(
  39. '#title' => t('Organism'),
  40. '#type' => t('select'),
  41. '#description' => t("Choose the organism to which these sequences are associated"),
  42. '#required' => TRUE,
  43. '#options' => $organisms,
  44. );
  45. // get the sequence ontology CV ID
  46. $values = array('name' => 'sequence');
  47. $cv = chado_select_record('cv', array('cv_id'), $values);
  48. $cv_id = $cv[0]->cv_id;
  49. $form['seqtype']= array(
  50. '#type' => 'textfield',
  51. '#title' => t('Sequence Type'),
  52. '#required' => TRUE,
  53. '#description' => t('Please enter the Sequence Ontology (SO) term name that describes the sequences in the FASTA file (e.g. gene, mRNA, protein, etc...)'),
  54. '#autocomplete_path' => "admin/tripal/chado/tripal_cv/cvterm/auto_name/$cv_id",
  55. );
  56. // get the list of organisms
  57. $sql = "SELECT L.library_id, L.name, CVT.name as type
  58. FROM {library} L
  59. INNER JOIN {cvterm} CVT ON L.type_id = CVT.cvterm_id
  60. ORDER BY name";
  61. $lib_rset = chado_query($sql);
  62. $libraries = array();
  63. $libraries[''] = '';
  64. while ($library = $lib_rset->fetchObject()) {
  65. $libraries[$library->library_id] = "$library->name ($library->type)";
  66. }
  67. // $form['library_id'] = array (
  68. // '#title' => t('Library'),
  69. // '#type' => t('select'),
  70. // '#description' => t("Choose the library to which these sequences are associated "),
  71. // '#required' => FALSE,
  72. // '#options' => $libraries,
  73. // '#weight' => 5,
  74. // );
  75. $form['method']= array(
  76. '#type' => 'radios',
  77. '#title' => 'Method',
  78. '#required' => TRUE,
  79. '#options' => array(
  80. t('Insert only'),
  81. t('Update only'),
  82. t('Insert and update'),
  83. ),
  84. '#description' => t('Select how features in the FASTA file are handled.
  85. Select "Insert only" to insert the new features. If a feature already
  86. exists with the same name or unique name and type then it is skipped.
  87. Select "Update only" to only update featues that already exist in the
  88. database. Select "Insert and Update" to insert features that do
  89. not exist and upate those that do.'),
  90. '#default_value' => 2,
  91. );
  92. $form['match_type']= array(
  93. '#type' => 'radios',
  94. '#title' => 'Name Match Type',
  95. '#required' => TRUE,
  96. '#options' => array(
  97. t('Name'),
  98. t('Unique name'),
  99. ),
  100. '#description' => t('Used for "updates only" or "insert and update" methods. Not required if method type is "insert".
  101. Feature data is stored in Chado with both a human-readable
  102. name and a unique name. If the features in your FASTA file are uniquely identified using
  103. a human-readable name then select the "Name" button. If your features are
  104. uniquely identified using the unique name then select the "Unique name" button. If you
  105. loaded your features first using the GFF loader then the unique name of each
  106. features were indicated by the "ID=" attribute and the name by the "Name=" attribute.
  107. By default, the FASTA loader will use the first word (character string
  108. before the first space) as the name for your feature. If
  109. this does not uniquely identify your feature consider specifying a regular expression in the advanced section below.
  110. Additionally, you may import both a name and a unique name for each sequence using the advanced options.'),
  111. '#default_value' => 1,
  112. );
  113. $form['analysis'] = array(
  114. '#type' => 'fieldset',
  115. '#title' => t('Analysis Used to Derive Features'),
  116. '#collapsed' => TRUE
  117. );
  118. $form['analysis']['desc'] = array(
  119. '#markup' => t("Why specify an analysis for a data load? All data comes
  120. from some place, even if downloaded from Genbank. By specifying
  121. analysis details for all data uploads, it allows an end user to reproduce the
  122. data set, but at least indicates the source of the data."),
  123. );
  124. // get the list of organisms
  125. $sql = "SELECT * FROM {analysis} ORDER BY name";
  126. $org_rset = chado_query($sql);
  127. $analyses = array();
  128. $analyses[''] = '';
  129. while ($analysis = $org_rset->fetchObject()) {
  130. $analyses[$analysis->analysis_id] = "$analysis->name ($analysis->program $analysis->programversion, $analysis->sourcename)";
  131. }
  132. $form['analysis']['analysis_id'] = array(
  133. '#title' => t('Analysis'),
  134. '#type' => t('select'),
  135. '#description' => t("Choose the analysis to which these features are associated"),
  136. '#required' => TRUE,
  137. '#options' => $analyses,
  138. );
  139. // Advanced Options
  140. $form['advanced'] = array(
  141. '#type' => 'fieldset',
  142. '#title' => t('Advanced Options'),
  143. '#collapsible' => TRUE,
  144. '#collapsed' => TRUE
  145. );
  146. $form['advanced']['re_help']= array(
  147. '#type' => 'item',
  148. '#value' => t('A regular expression is an advanced method for extracting information from a string of text.
  149. Your FASTA file may contain both a human-readable name and a unique name for each sequence.
  150. If you want to import
  151. both the name and unique name for all sequences, then you must provide regular expressions
  152. so that the loader knows how to separate them.
  153. Otherwise the name and uniquename will be the same.
  154. By default, this loader will use the first word in the definition
  155. lines of the FASTA file
  156. as the name or unique name of the feature.'),
  157. );
  158. $form['advanced']['re_name']= array(
  159. '#type' => 'textfield',
  160. '#title' => t('Regular expression for the name'),
  161. '#required' => FALSE,
  162. '#description' => t('Enter the regular expression that will extract the
  163. feature name from the FASTA definition line. For example, for a
  164. defintion line with a name and unique name separated by a bar \'|\' (>seqname|uniquename),
  165. the regular expression for the name would be, "^(.*?)\|.*$".'),
  166. );
  167. $form['advanced']['re_uname']= array(
  168. '#type' => 'textfield',
  169. '#title' => t('Regular expression for the unique name'),
  170. '#required' => FALSE,
  171. '#description' => t('Enter the regular expression that will extract the
  172. feature name from the FASTA definition line. For example, for a
  173. defintion line with a name and unique name separated by a bar \'|\' (>seqname|uniquename),
  174. the regular expression for the unique name would be "^.*?\|(.*)$").'),
  175. );
  176. // Advanced database cross-reference optoins
  177. $form['advanced']['db'] = array(
  178. '#type' => 'fieldset',
  179. '#title' => t('External Database Reference'),
  180. '#weight' => 6,
  181. '#collapsed' => TRUE
  182. );
  183. $form['advanced']['db']['re_accession']= array(
  184. '#type' => 'textfield',
  185. '#title' => t('Regular expression for the accession'),
  186. '#required' => FALSE,
  187. '#description' => t('Enter the regular expression that will extract the accession for the external database for each feature from the FASTA definition line.'),
  188. '#weight' => 2
  189. );
  190. // get the list of databases
  191. $sql = "SELECT * FROM {db} ORDER BY name";
  192. $db_rset = chado_query($sql);
  193. $dbs = array();
  194. $dbs[''] = '';
  195. while ($db = $db_rset->fetchObject()) {
  196. $dbs[$db->db_id] = "$db->name";
  197. }
  198. $form['advanced']['db']['db_id'] = array(
  199. '#title' => t('External Database'),
  200. '#type' => t('select'),
  201. '#description' => t("Plese choose an external database for which these sequences have a cross reference."),
  202. '#required' => FALSE,
  203. '#options' => $dbs,
  204. '#weight' => 1,
  205. );
  206. $form['advanced']['relationship'] = array(
  207. '#type' => 'fieldset',
  208. '#title' => t('Relationships'),
  209. '#weight' => 6,
  210. '#collapsed' => TRUE
  211. );
  212. $rels = array();
  213. $rels[''] = '';
  214. $rels['part_of'] = 'part of';
  215. $rels['derives_from'] = 'produced by';
  216. // Advanced references options
  217. $form['advanced']['relationship']['rel_type']= array(
  218. '#title' => t('Relationship Type'),
  219. '#type' => t('select'),
  220. '#description' => t("Use this option to create associations, or relationships between the
  221. features of this FASTA file and existing features in the database. For
  222. example, to associate a FASTA file of peptides to existing genes or transcript sequence,
  223. select the type 'produced by'. For a CDS sequences select the type 'part of'"),
  224. '#required' => FALSE,
  225. '#options' => $rels,
  226. '#weight' => 5,
  227. );
  228. $form['advanced']['relationship']['re_subject']= array(
  229. '#type' => 'textfield',
  230. '#title' => t('Regular expression for the parent'),
  231. '#required' => FALSE,
  232. '#description' => t('Enter the regular expression that will extract the unique
  233. name needed to identify the existing sequence for which the
  234. relationship type selected above will apply.'),
  235. '#weight' => 6
  236. );
  237. $form['advanced']['relationship']['parent_type']= array(
  238. '#type' => 'textfield',
  239. '#title' => t('Parent Type'),
  240. '#required' => FALSE,
  241. '#description' => t('Please enter the Sequence Ontology term for the parent. For example
  242. if the FASTA file being loaded is a set of proteins that are
  243. products of genes, then use the SO term \'gene\' or \'transcript\' or equivalent. However,
  244. this type must match the type for already loaded features.'),
  245. '#weight' => 7
  246. );
  247. $form['button'] = array(
  248. '#type' => 'submit',
  249. '#value' => t('Import FASTA file'),
  250. '#weight' => 10,
  251. );
  252. return $form;
  253. }
  254. /**
  255. * Validate the fasta loader job form
  256. *
  257. * @ingroup fasta_loader
  258. */
  259. function tripal_feature_fasta_load_form_validate($form, &$form_state) {
  260. $fasta_file = trim($form_state['values']['fasta_file']);
  261. $organism_id = $form_state['values']['organism_id'];
  262. $type = trim($form_state['values']['seqtype']);
  263. $method = trim($form_state['values']['method']);
  264. $match_type = trim($form_state['values']['match_type']);
  265. $re_name = trim($form_state['values']['re_name']);
  266. $re_uname = trim($form_state['values']['re_uname']);
  267. $re_accession = trim($form_state['values']['re_accession']);
  268. $db_id = $form_state['values']['db_id'];
  269. $rel_type = $form_state['values']['rel_type'];
  270. $re_subject = trim($form_state['values']['re_subject']);
  271. $parent_type = trim($form_state['values']['parent_type']);
  272. if ($method == 0) {
  273. $method = 'Insert only';
  274. }
  275. if ($method == 1) {
  276. $method = 'Update only';
  277. }
  278. if ($method == 2) {
  279. $method = 'Insert and update';
  280. }
  281. if ($match_type == 0) {
  282. $match_type = 'Name';
  283. }
  284. if ($match_type == 1) {
  285. $match_type = 'Unique name';
  286. }
  287. if ($re_name and !$re_uname and strcmp($match_type, 'Unique name')==0) {
  288. form_set_error('re_uname', t("You must provide a regular expression to identify the sequence unique name"));
  289. }
  290. if (!$re_name and $re_uname and strcmp($match_type, 'Name')==0) {
  291. form_set_error('re_name', t("You must provide a regular expression to identify the sequence name"));
  292. }
  293. // check to see if the file is located local to Drupal
  294. $fasta_file = trim($fasta_file);
  295. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $fasta_file;
  296. if (!file_exists($dfile)) {
  297. // if not local to Drupal, the file must be someplace else, just use
  298. // the full path provided
  299. $dfile = $fasta_file;
  300. }
  301. if (!file_exists($dfile)) {
  302. form_set_error('fasta_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."));
  303. }
  304. // make sure if a relationship is specified that all fields are provided.
  305. if (($rel_type or $parent_type) and !$re_subject) {
  306. form_set_error('re_subject', t("Please provide a regular expression for the parent"));
  307. }
  308. if (($rel_type or $re_subject) and !$parent_type) {
  309. form_set_error('parent_type', t("Please provide a SO term for the parent"));
  310. }
  311. if (($parent_type or $re_subject) and !$rel_type) {
  312. form_set_error('rel_type', t("Please select a relationship type"));
  313. }
  314. // make sure if a database is specified that all fields are provided
  315. if ($db_id and !$re_accession) {
  316. form_set_error('re_accession', t("Please provide a regular expression for the accession"));
  317. }
  318. if ($re_accession and !$db_id) {
  319. form_set_error('db_id', t("Please select a database"));
  320. }
  321. // check to make sure the types exists
  322. $cvtermsql = "SELECT CVT.cvterm_id
  323. FROM {cvterm} CVT
  324. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  325. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  326. WHERE cv.name = :cvname and (CVT.name = :name or CVTS.synonym = :synonym)";
  327. $cvterm = chado_query($cvtermsql, array(':cvname' => 'sequence', ':name' => $type, ':synonym' => $type))->fetchObject();
  328. if (!$cvterm) {
  329. form_set_error('type', t("The Sequence Ontology (SO) term selected for the sequence type is not available in the database. Please check spelling or select another."));
  330. }
  331. if ($rel_type) {
  332. $cvterm = chado_query($cvtermsql, array(':cvname' => 'sequence', ':name' => $parent_type, ':synonym' => $parent_type))->fetchObject();
  333. if (!$cvterm) {
  334. form_set_error('parent_type', t("The Sequence Ontology (SO) term selected for the parent relationship is not available in the database. Please check spelling or select another."));
  335. }
  336. }
  337. // check to make sure the 'relationship' and 'sequence' ontologies are loaded
  338. $form_state['storage']['dfile'] = $dfile;
  339. }
  340. /**
  341. * Submit a fasta loading job
  342. *
  343. * @ingroup fasta_loader
  344. */
  345. function tripal_feature_fasta_load_form_submit($form, &$form_state) {
  346. global $user;
  347. $dfile = $form_state['storage']['dfile'];
  348. $organism_id = $form_state['values']['organism_id'];
  349. $type = trim($form_state['values']['seqtype']);
  350. $method = trim($form_state['values']['method']);
  351. $match_type = trim($form_state['values']['match_type']);
  352. $re_name = trim($form_state['values']['re_name']);
  353. $re_uname = trim($form_state['values']['re_uname']);
  354. $re_accession = trim($form_state['values']['re_accession']);
  355. $db_id = $form_state['values']['db_id'];
  356. $rel_type = $form_state['values']['rel_type'];
  357. $re_subject = trim($form_state['values']['re_subject']);
  358. $parent_type = trim($form_state['values']['parent_type']);
  359. $analysis_id = $form_state['values']['analysis_id'];
  360. if ($method == 0) {
  361. $method = 'Insert only';
  362. }
  363. if ($method == 1) {
  364. $method = 'Update only';
  365. }
  366. if ($method == 2) {
  367. $method = 'Insert and update';
  368. }
  369. if ($match_type == 0) {
  370. $match_type = 'Name';
  371. }
  372. if ($match_type == 1) {
  373. $match_type = 'Unique name';
  374. }
  375. $args = array($dfile, $organism_id, $type, $library_id, $re_name, $re_uname,
  376. $re_accession, $db_id, $rel_type, $re_subject, $parent_type, $method,
  377. $user->uid, $analysis_id, $match_type);
  378. $fname = preg_replace("/.*\/(.*)/", "$1", $dfile);
  379. tripal_add_job("Import FASTA file: $fname", 'tripal_feature',
  380. 'tripal_feature_load_fasta', $args, $user->uid);
  381. }
  382. /**
  383. * Actually load a fasta file. This is the function called by tripal jobs
  384. *
  385. * @param $dfile
  386. * The full path to the fasta file to load
  387. * @param $organism_id
  388. * The organism_id of the organism these features are from
  389. * @param $type
  390. * The type of features contained in the fasta file
  391. * @param $library_id
  392. * (Optional) The library_id to associate the features with
  393. * @param $re_name
  394. * A regular expression to extract the feature.name from the fasta header
  395. * @param $re_uname
  396. * A regular expression to extract the feature.uniquename from the fasta header
  397. * @param $re_accession
  398. * A regular expression to extract the accession of the feature.dbxref_id
  399. * @param $db_id
  400. * The db_id of the above dbxref
  401. * @param $rel_type
  402. * The type of relationship when creating a feature_relationship between this
  403. * feature (object) and an extracted subject
  404. * @param $re_subject
  405. * The regular expression to extract the uniquename of the feature to be the subject
  406. * of the above specified relationship
  407. * @param $parent_type
  408. * The type of the parent feature
  409. * @param $method
  410. * The method of feature adding. (ie: 'Insert only', 'Update only', 'Insert and update')
  411. * @param $uid
  412. * The user id of the user who submitted the job
  413. * @param $analysis_id
  414. * The analysis_id to associate the features in this fasta file with
  415. * @param $match_type
  416. * Whether to match existing features based on the 'Name' or 'Unique name'
  417. * @param $job = NULL
  418. * The tripal job
  419. *
  420. * @ingroup fasta_loader
  421. */
  422. function tripal_feature_load_fasta($dfile, $organism_id, $type,
  423. $library_id, $re_name, $re_uname, $re_accession, $db_id, $rel_type,
  424. $re_subject, $parent_type, $method, $uid, $analysis_id,
  425. $match_type, $job = NULL) {
  426. $transaction = db_transaction();
  427. print "\nNOTE: Loading of this GFF file is performed using a database transaction. \n" .
  428. "If the load fails or is terminated prematurely then the entire set of \n" .
  429. "insertions/updates is rolled back and will not be found in the database\n\n";
  430. try {
  431. // first get the type for this sequence
  432. $cvtermsql = "SELECT CVT.cvterm_id
  433. FROM {cvterm} CVT
  434. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  435. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  436. WHERE cv.name = :cvname and (CVT.name = :name or CVTS.synonym = :synonym)";
  437. $cvterm = chado_query($cvtermsql, array(':cvname' => 'sequence', ':name' => $type, ':synonym' => $type))->fetchObject();
  438. if (!$cvterm) {
  439. tripal_report_error("T_fasta_loader", TRIPAL_ERROR, "Cannot find the term type: '%type'", array('%type' => $type));
  440. return 0;
  441. }
  442. if ($parent_type) {
  443. $parentcvterm = chado_query($cvtermsql, array(':cvname' => 'sequence', ':name' => $parent_type, ':synonym' => $parent_type))->fetchObject();
  444. if (!$parentcvterm) {
  445. tripal_report_error("T_fasta_loader", TRIPAL_ERROR, "Cannot find the paretne term type: '%type'", array('%type' => $parentcvterm));
  446. return 0;
  447. }
  448. }
  449. if ($rel_type) {
  450. $relcvterm = chado_query($cvtermsql, array(':cvname' => 'relationship', ':name' => $rel_type, ':synonym' => $rel_type))->fetchObject();
  451. if (!$relcvterm) {
  452. tripal_report_error("T_fasta_loader", TRIPAL_ERROR, "Cannot find the relationship term type: '%type'", array('%type' => $relcvterm));
  453. return 0;
  454. }
  455. }
  456. print "Opening FASTA file $dfile\n";
  457. //$lines = file($dfile, FILE_SKIP_EMPTY_LINES);
  458. $fh = fopen($dfile, 'r');
  459. if (!$fh) {
  460. tripal_report_error('T_fasta_loader', TRIPAL_ERROR, "cannot open file: %dfile", array('%dfile' => $dfile));
  461. return 0;
  462. }
  463. $filesize = filesize($dfile);
  464. $i = 0;
  465. $name = '';
  466. $uname = '';
  467. $residues = '';
  468. $interval = intval($filesize * 0.01);
  469. if ($interval < 1) {
  470. $interval = 1;
  471. }
  472. $inv_read = 0;
  473. // we need to get the table schema to make sure we don't overrun the
  474. // size of fields with what our regular expressions retrieve
  475. $feature_tbl = chado_get_schema('feature');
  476. $dbxref_tbl = chado_get_schema('dbxref');
  477. //foreach ($lines as $line_num => $line) {
  478. while ($line = fgets($fh)) {
  479. $i++; // update the line count
  480. $num_read += drupal_strlen($line);
  481. $intv_read += drupal_strlen($line);
  482. // if we encounter a definition line then get the name, uniquename,
  483. // accession and relationship subject from the definition line
  484. if (preg_match('/^>/', $line)) {
  485. // if we have a feature name then we are starting a new sequence
  486. // so lets handle the previous one before moving on
  487. if ($name or $uname) {
  488. tripal_feature_fasta_loader_handle_feature($name, $uname, $db_id,
  489. $accession, $subject, $rel_type, $parent_type, $analysis_id, $organism_id, $cvterm,
  490. $source, $residues, $method, $re_name, $match_type, $parentcvterm, $relcvterm);
  491. $residues = '';
  492. $name = '';
  493. $uname = '';
  494. }
  495. $line = preg_replace("/^>/", '', $line); // remove the > symbol from the defline
  496. // get the feature name
  497. if ($re_name) {
  498. if (!preg_match("/$re_name/", $line, $matches)) {
  499. tripal_report_error('trp-fasta', "ERROR: Regular expression for the feature name finds nothing. Line %line.", array('%line' => $i), 'error');
  500. }
  501. elseif (strlen($matches[1]) > $feature_tbl['fields']['name']['length']) {
  502. tripal_report_error('trp-fasta', "WARNING: Regular expression retrieves a value too long for the feature name. Line %line.", array('%line' => $i), 'error');
  503. }
  504. else {
  505. $name = trim($matches[1]);
  506. }
  507. }
  508. else {
  509. // if the match_type is name and no regular expression was provided
  510. // then use the first word as the name, otherwise we don't set the name
  511. if (strcmp($match_type, 'Name')==0) {
  512. if (preg_match("/^\s*(.*?)[\s\|].*$/", $line, $matches)) {
  513. if (strlen($matches[1]) > $feature_tbl['fields']['name']['length']) {
  514. tripal_report_error('trp-fasta', "WARNING: Regular expression retrieves a feature name too long for the feature name. Line %line.", array('%line' => $i), 'error');
  515. }
  516. else {
  517. $name = trim($matches[1]);
  518. }
  519. }
  520. else {
  521. tripal_report_error('trp-fasta', "ERROR: Cannot find a feature name. Line %line.", array('%line' => $i), 'error');
  522. }
  523. }
  524. }
  525. // get the feature unique name
  526. if ($re_uname) {
  527. if (!preg_match("/$re_uname/", $line, $matches)) {
  528. tripal_report_error('trp-fasta', "ERROR: Regular expression for the feature unique name finds nothing. Line %line.", array('%line' => $i), 'error');
  529. }
  530. $uname = trim($matches[1]);
  531. }
  532. else {
  533. // if the match_type is name and no regular expression was provided
  534. // then use the first word as the name, otherwise, we don't set the unqiuename
  535. if (strcmp($match_type, 'Unique name')==0) {
  536. if (preg_match("/^\s*(.*?)[\s\|].*$/", $line, $matches)) {
  537. $uname = trim($matches[1]);
  538. }
  539. else {
  540. tripal_report_error('trp-fasta', "ERROR: Cannot find a feature unique name. Line %line.", array('%line' => $i), 'error');
  541. }
  542. }
  543. }
  544. // get the accession
  545. preg_match("/$re_accession/", $line, $matches);
  546. if (strlen($matches[1]) > $dbxref_tbl['fields']['accession']['length']) {
  547. tripal_report_error('trp-fasta', "WARNING: Regular expression retrieves an accession too long for the feature name. Cannot add cross reference. Line %line.", array('%line' => $i), 'warning');
  548. }
  549. else {
  550. $accession = trim($matches[1]);
  551. }
  552. // get the relationship subject
  553. preg_match("/$re_subject/", $line, $matches);
  554. $subject = trim($matches[1]);
  555. }
  556. else {
  557. $residues .= trim($line);
  558. // update the job status every % features
  559. if ($job and $intv_read >= $interval) {
  560. $intv_read = 0;
  561. $percent = sprintf("%.2f", ($num_read / $filesize) * 100);
  562. if ($name) {
  563. print "Parsing Line $i (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes. Current feature: $name\r";
  564. }
  565. else {
  566. print "Parsing Line $i (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes. Current feature: $uname\r";
  567. }
  568. tripal_set_job_progress($job, intval(($num_read / $filesize) * 100));
  569. }
  570. }
  571. }
  572. // now load the last sequence in the file
  573. tripal_feature_fasta_loader_handle_feature($name, $uname, $db_id,
  574. $accession, $subject, $rel_type, $parent_type, $analysis_id, $organism_id, $cvterm,
  575. $source, $residues, $method, $re_name, $match_type, $parentcvterm, $relcvterm);
  576. }
  577. catch (Exception $e) {
  578. print "\n"; // make sure we start errors on new line
  579. watchdog_exception('T_fasta_loader', $e);
  580. $transaction->rollback();
  581. print "FAILED: Rolling back database changes...\n";
  582. }
  583. print "\nDone\n";
  584. }
  585. /**
  586. * A helper function for tripal_feature_load_fasta() to load a single feature
  587. *
  588. * @param $name
  589. * @param $uname
  590. * @param $db_id
  591. * @param $accession
  592. * @param $parent
  593. * @param $rel_type
  594. * @param $parent_type
  595. * @param $analysis_id
  596. * @param $organism_id
  597. * @param $cvterm
  598. * @param $source
  599. * @param $residues
  600. * @param $method
  601. * @param $re_name
  602. * @param $match_type
  603. * @param $parentcvterm
  604. * @param $relcvterm
  605. *
  606. * @ingroup fasta_loader
  607. */
  608. function tripal_feature_fasta_loader_handle_feature($name, $uname, $db_id, $accession,
  609. $parent, $rel_type, $parent_type, $analysis_id, $organism_id, $cvterm,
  610. $source, $residues, $method, $re_name, $match_type, $parentcvterm, $relcvterm) {
  611. // check to see if this feature already exists if the match_type is 'Name'
  612. if (strcmp($match_type, 'Name')==0) {
  613. $values = array(
  614. 'organism_id' => $organism_id,
  615. 'name' => $name,
  616. 'type_id' => $cvterm->cvterm_id,
  617. );
  618. $options = array('statement_name' => 'sel_feature_ornaty');
  619. $results = chado_select_record('feature', array('feature_id'), $values, $options);
  620. if (count($results) > 1) {
  621. tripal_report_error('T_fasta_loader', "Multiple features exist with the name '%name' of type
  622. '%type' for the organism. skipping", array('%name' => $name, '%type' => $type));
  623. return 0;
  624. }
  625. if (count($results) == 1) {
  626. $feature = $results[0];
  627. }
  628. }
  629. // check to see if this feature already exists if the match_type is 'Unique Name'
  630. if (strcmp($match_type, 'Unique name')==0) {
  631. $values = array(
  632. 'organism_id' => $organism_id,
  633. 'uniquename' => $uname,
  634. 'type_id' => $cvterm->cvterm_id,
  635. );
  636. $options = array('statement_name' => 'sel_feature_oruqty');
  637. $results = chado_select_record('feature', array('feature_id'), $values, $options);
  638. if (count($results) > 1) {
  639. tripal_report_error('T_fasta_loader', "Multiple features exist with the name '%name' of type
  640. '%type' for the organism. skipping", array('%name' => $name, '%type' => $type));
  641. return 0;
  642. }
  643. if (count($results) == 1) {
  644. $feature = $results[0];
  645. }
  646. // if the feature exists but this is an "insert only" method then skip this feature
  647. if ($feature and (strcmp($method, 'Insert only')==0)) {
  648. tripal_report_error('T_fasta_loader', TRIPAL_WARNING, "Feature already exists '%name' ('%uname') while matching on %type. Skipping insert.",
  649. array('%name' => $name, '%uname' => $uname, '%type' => drupal_strtolower($match_type)));
  650. return 0;
  651. }
  652. }
  653. // if we don't have a feature and we're doing an insert then do the insert
  654. $inserted = 0;
  655. if (!$feature and (strcmp($method, 'Insert only')==0 or strcmp($method, 'Insert and update')==0)) {
  656. // if we have a unique name but not a name then set them to be the same and vice versa
  657. if (!$uname) {
  658. $uname = $name;
  659. }
  660. elseif (!$name) {
  661. $name = $uname;
  662. }
  663. // insert the feature
  664. $values = array(
  665. 'organism_id' => $organism_id,
  666. 'name' => $name,
  667. 'uniquename' => $uname,
  668. 'residues' => $residues,
  669. 'seqlen' => drupal_strlen($residues),
  670. 'md5checksum' => md5($residues),
  671. 'type_id' => $cvterm->cvterm_id,
  672. 'is_analysis' => 'FALSE',
  673. 'is_obsolete' => 'FALSE',
  674. );
  675. $options = array('statement_name' => 'ins_feature_all');
  676. $success = chado_insert_record('feature', $values, $options);
  677. if (!$success) {
  678. tripal_report_error('T_fasta_loader', TRIPAL_ERROR, "Failed to insert feature '%name (%uname)'",
  679. array('%name' => $name, '%uname' => $numane));
  680. return 0;
  681. }
  682. // now get the feature we just inserted
  683. $values = array(
  684. 'organism_id' => $organism_id,
  685. 'uniquename' => $uname,
  686. 'type_id' => $cvterm->cvterm_id,
  687. );
  688. $options = array('statement_name' => 'sel_feature_oruqty');
  689. $results = chado_select_record('feature', array('feature_id'), $values, $options);
  690. if (count($results) == 1) {
  691. $inserted = 1;
  692. $feature = $results[0];
  693. }
  694. else {
  695. tripal_report_error('T_fasta_loader', TRIPAL_ERROR, "Failed to retreive newly inserted feature '%name (%uname)'",
  696. array('%name' => $name, '%uname' => $numane));
  697. return 0;
  698. }
  699. }
  700. // if we don't have a feature and the user wants to do an update then fail
  701. if (!$feature and (strcmp($method, 'Update only')==0 or drupal_strcmp($method, 'Insert and update')==0)) {
  702. tripal_report_error('T_fasta_loader', TRIPAL_ERROR, "Failed to find feature '%name' ('%uname') while matching on " .
  703. drupal_strtolower($match_type), array('%name' => $name, '%uname' => $uname));
  704. return 0;
  705. }
  706. // if we do have a feature and this is an update then proceed with the update
  707. if ($feature and !$inserted and (strcmp($method, 'Update only')==0 or strcmp($method, 'Insert and update')==0)) {
  708. // if the user wants to match on the Name field
  709. if (strcmp($match_type, 'Name')==0) {
  710. // if we're matching on the name but do not have a unique name then we don't want to update the uniquename.
  711. $values = array();
  712. if ($uname) {
  713. // first check to make sure that by changing the unique name of this feature that we won't conflict with
  714. // another existing feature of the same name
  715. $values = array(
  716. 'organism_id' => $organism_id,
  717. 'uniquename' => $uname,
  718. 'type_id' => $cvterm->cvterm_id,
  719. );
  720. $options = array('statement_name' => 'sel_feature_oruqty');
  721. $results = chado_select_record('feature', array('feature_id'), $values, $options);
  722. if (count($results) > 0) {
  723. tripal_report_error('T_fasta_loader', "Cannot update the feature '%name' with a uniquename of '%uname' and type of '%type' as it
  724. conflicts with an existing feature with the same uniquename and type.",
  725. array('%name' => $name, '%uname' => $uname, '%type' => $type));
  726. return 0;
  727. }
  728. // the changes to the uniquename don't conflict so proceed with the update
  729. $values = array(
  730. 'uniquename' => $uname,
  731. 'residues' => $residues,
  732. 'seqlen' => drupal_strlen($residues),
  733. 'md5checksum' => md5($residues),
  734. 'is_analysis' => 'false',
  735. 'is_obsolete' => 'false',
  736. );
  737. $match = array(
  738. 'name' => $name,
  739. 'organism_id' => $organism_id,
  740. 'type_id' => $cvterm->cvterm_id,
  741. );
  742. $options = array('statement_name' => 'upd_feature_resemdisis_naorty_un');
  743. }
  744. // if we do not have a new unique name then don't change the existing uniquename field
  745. else {
  746. $values = array(
  747. 'residues' => $residues,
  748. 'seqlen' => drupal_strlen($residues),
  749. 'md5checksum' => md5($residues),
  750. 'is_analysis' => 'false',
  751. 'is_obsolete' => 'false',
  752. );
  753. $match = array(
  754. 'name' => $name,
  755. 'organism_id' => $organism_id,
  756. 'type_id' => $cvterm->cvterm_id,
  757. );
  758. $options = array('statement_name' => 'upd_feature_unresemdisis_naorty');
  759. }
  760. // perform the update
  761. $success = chado_update_record('feature', $match, $values, $options);
  762. if (!$success) {
  763. tripal_report_error('T_fasta_loader', TRIPAL_ERROR,
  764. "Failed to update feature '%name' ('%name')",
  765. array('%name' => $name, '%uiname' => $uname));
  766. return 0;
  767. }
  768. }
  769. if (strcmp($match_type, 'Unique name')==0) {
  770. // if we're matching on the uniquename but do not have a new name then we don't want to update the name.
  771. $values = array();
  772. if ($name) {
  773. $values = array(
  774. 'name' => $name,
  775. 'residues' => $residues,
  776. 'seqlen' => drupal_strlen($residues),
  777. 'md5checksum' => md5($residues),
  778. 'is_analysis' => 'false',
  779. 'is_obsolete' => 'false',
  780. );
  781. $match = array(
  782. 'uniquename' => $uname,
  783. 'organism_id' => $organism_id,
  784. 'type_id' => $cvterm->cvterm_id,
  785. );
  786. $options = array('statement_name' => 'upd_feature_resemdisis_unorty_na');
  787. }
  788. // if we have a unique name then update it after matching by the name
  789. else {
  790. $values = array(
  791. 'residues' => $residues,
  792. 'seqlen' => drupal_strlen($residues),
  793. 'md5checksum' => md5($residues),
  794. 'is_analysis' => 'false',
  795. 'is_obsolete' => 'false',
  796. );
  797. $match = array(
  798. 'uniquename' => $uname,
  799. 'organism_id' => $organism_id,
  800. 'type_id' => $cvterm->cvterm_id,
  801. );
  802. $options = array('statement_name' => 'upd_feature_naresemdisis_unorty');
  803. }
  804. $success = chado_update_record('feature', $match, $values, $options);
  805. if (!$success) {
  806. tripal_report_error('T_fasta_loader', TRIPAL_ERROR, "Failed to update feature '%name' ('%name')",
  807. array('%name' => $name, '%uiname' => $uname));
  808. return 0;
  809. }
  810. }
  811. }
  812. // add in the analysis link
  813. if ($analysis_id) {
  814. // if the association doens't alredy exist then add one
  815. $values = array(
  816. 'analysis_id' => $analysis_id,
  817. 'feature_id' => $feature->feature_id,
  818. );
  819. $sel_options = array('statement_name' => 'sel_analysisfeature_anfe');
  820. $results = chado_select_record('analysisfeature', array('analysisfeature_id'), $values, $sel_options);
  821. if (count($results) == 0) {
  822. $ins_options = array('statement_name' => 'ins_analysisfeature_anfe');
  823. $success = chado_insert_record('analysisfeature', $values, $ins_options);
  824. if (!$success) {
  825. tripal_report_error('T_fasta_loader', TRIPAL_ERROR, "Failed to associate analysis and feature '%name' ('%name')",
  826. array('%name' => $name, '%uname' => $uname));
  827. return 0;
  828. }
  829. }
  830. }
  831. // now add the database cross reference
  832. if ($db_id) {
  833. // check to see if this accession reference exists, if not add it
  834. $values = array(
  835. 'db_id' => $db_id,
  836. 'accession' => $accession
  837. );
  838. $sel_options = array('statement_name' => 'sel_dbxref_dbac');
  839. $results = chado_select_record('dbxref', array('dbxref_id'), $values, $sel_options);
  840. // if the accession doesn't exist then add it
  841. if (count($results) == 0) {
  842. $ins_options = array('statement_name' => 'ins_dbxref_dbac');
  843. $results = chado_insert_record('dbxref', $values, $ins_options);
  844. if (!$results) {
  845. tripal_report_error('T_fasta_loader', TRIPAL_ERROR, "Failed to add database accession '%accession'",
  846. array('%accession' => $accession));
  847. return 0;
  848. }
  849. $results = chado_select_record('dbxref', array('dbxref_id'), $values, $sel_options);
  850. if (count($results) == 1) {
  851. $dbxref = $results[0];
  852. }
  853. else {
  854. tripal_report_error('T_fasta_loader', TRIPAL_ERROR, "Failed to retreive newly inserted dbxref '%name (%uname)'",
  855. array('%name' => $name, '%uname' => $numane));
  856. return 0;
  857. }
  858. }
  859. else {
  860. $dbxref = $results[0];
  861. }
  862. // check to see if the feature dbxref record exists if not, then add it
  863. $values = array(
  864. 'feature_id' => $feature->feature_id,
  865. 'dbxref_id' => $dbxref->dbxref_id
  866. );
  867. $sel_options = array('statement_name' => 'sel_featuredbxref_fedb');
  868. $results = chado_select_record('feature_dbxref', array('feature_dbxref_id'), $values, $sel_options);
  869. if (count($results) == 0) {
  870. $ins_options = array('statement_name' => 'ins_featuredbxref_fedb');
  871. $success = chado_insert_record('feature_dbxref', $values, $ins_options);
  872. if (!$success) {
  873. tripal_report_error('T_fasta_loader', TRIPAL_ERROR, "Failed to add associate database accession '%accession' with feature",
  874. array('%accession' => $accession));
  875. return 0;
  876. }
  877. }
  878. }
  879. // now add in the relationship if one exists. If not, then add it
  880. if ($rel_type) {
  881. $values = array(
  882. 'organism_id' => $organism_id,
  883. 'uniquename' => $parent,
  884. 'type_id' => $parentcvterm->cvterm_id,
  885. );
  886. $options = array('statement_name' => 'sel_feature_oruqty');
  887. $results = chado_select_record('feature', array('feature_id'), $values, $options);
  888. if (count($results) != 1) {
  889. tripal_report_error('T_fasta_loader', "Cannot find a unique fature for the parent '%parent' of type
  890. '%type' for the feature.", array('%parent' => $parent, '%type' => $parent_type));
  891. return 0;
  892. }
  893. $parent_feature = $results[0];
  894. // check to see if the relationship already exists if not then add it
  895. $values = array(
  896. 'subject_id' => $feature->feature_id,
  897. 'object_id' => $parent_feature->feature_id,
  898. 'type_id' => $relcvterm->cvterm_id,
  899. );
  900. $sel_options = array('statement_name' => 'sel_featurerelationship_suojty');
  901. $results = chado_select_record('feature_relationship', array('feature_relationship_id'), $values, $sel_options);
  902. if (count($results) == 0) {
  903. $ins_options = array('statement_name' => 'ins_featurerelationship_suojty');
  904. $success = chado_insert_record('feature_relationship', $values, $ins_options);
  905. if (!$success) {
  906. tripal_report_error('T_fasta_loader', TRIPAL_ERROR, "Failed to add associate database accession '%accession' with feature",
  907. array('%accession' => $accession));
  908. return 0;
  909. }
  910. }
  911. }
  912. }