FASTAImporter.inc 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. <?php
  2. class FASTAImporter extends TripalImporter {
  3. /**
  4. * The name of this loader. This name will be presented to the site
  5. * user.
  6. */
  7. public static $name = 'Chado FASTA Loader';
  8. /**
  9. * The machine name for this loader. This name will be used to construct
  10. * the URL for the loader.
  11. */
  12. public static $machine_name = 'chado_fasta_loader';
  13. /**
  14. * A brief description for this loader. This description will be
  15. * presented to the site user.
  16. */
  17. public static $description = 'Load sequences from a multi-FASTA file into Chado';
  18. /**
  19. * An array containing the extensions of allowed file types.
  20. */
  21. public static $file_types = array('fasta', 'txt', 'fa', 'aa', 'pep', 'nuc', 'faa', 'fna');
  22. /**
  23. * Provides information to the user about the file upload. Typically this
  24. * may include a description of the file types allowed.
  25. */
  26. public static $upload_description = 'Please provide the FASTA file. The file must have a .fasta extension.';
  27. /**
  28. * The title that should appear above the file upload section.
  29. */
  30. public static $upload_title = 'FASTA Upload';
  31. /**
  32. * Text that should appear on the button at the bottom of the importer
  33. * form.
  34. */
  35. public static $button_text = 'Import FASTA file';
  36. /**
  37. * Indicates the methods that the file uploader will support.
  38. */
  39. public static $methods = array(
  40. // Allow the user to upload a file to the server.
  41. 'file_upload' => TRUE,
  42. // Allow the user to provide the path on the Tripal server for the file.
  43. 'file_local' => TRUE,
  44. // Allow the user to provide a remote URL for the file.
  45. 'file_remote' => TRUE,
  46. );
  47. /**
  48. * @see TripalImporter::form()
  49. */
  50. public function form($form, &$form_state) {
  51. // get the list of organisms
  52. $sql = "SELECT * FROM {organism} ORDER BY genus, species";
  53. $org_rset = chado_query($sql);
  54. $organisms = array();
  55. $organisms[''] = '';
  56. while ($organism = $org_rset->fetchObject()) {
  57. $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
  58. }
  59. $form['organism_id'] = array(
  60. '#title' => t('Organism'),
  61. '#type' => t('select'),
  62. '#description' => t("Choose the organism to which these sequences are associated"),
  63. '#required' => TRUE,
  64. '#options' => $organisms
  65. );
  66. // get the sequence ontology CV ID
  67. $values = array('name' => 'sequence');
  68. $cv = chado_select_record('cv', array('cv_id'), $values);
  69. $cv_id = $cv[0]->cv_id;
  70. $form['seqtype'] = array(
  71. '#type' => 'textfield',
  72. '#title' => t('Sequence Type'),
  73. '#required' => TRUE,
  74. '#description' => t('Please enter the Sequence Ontology (SO) term name that describes the sequences in the FASTA file (e.g. gene, mRNA, polypeptide, etc...)'),
  75. '#autocomplete_path' => "admin/tripal/storage/chado/auto_name/cvterm/$cv_id"
  76. );
  77. $form['method'] = array(
  78. '#type' => 'radios',
  79. '#title' => 'Method',
  80. '#required' => TRUE,
  81. '#options' => array(
  82. t('Insert only'),
  83. t('Update only'),
  84. t('Insert and update')
  85. ),
  86. '#description' => t('Select how features in the FASTA file are handled.
  87. Select "Insert only" to insert the new features. If a feature already
  88. exists with the same name or unique name and type then it is skipped.
  89. Select "Update only" to only update featues that already exist in the
  90. database. Select "Insert and Update" to insert features that do
  91. not exist and upate those that do.'),
  92. '#default_value' => 2
  93. );
  94. $form['match_type'] = array('#type' => 'radios','#title' => 'Name Match Type','#required' => TRUE,
  95. '#options' => array(t('Name'),t('Unique name')
  96. ),
  97. '#description' => t('Used for "updates only" or "insert and update" methods. Not required if method type is "insert".
  98. Feature data is stored in Chado with both a human-readable
  99. name and a unique name. If the features in your FASTA file are uniquely identified using
  100. a human-readable name then select the "Name" button. If your features are
  101. uniquely identified using the unique name then select the "Unique name" button. If you
  102. loaded your features first using the GFF loader then the unique name of each
  103. features were indicated by the "ID=" attribute and the name by the "Name=" attribute.
  104. By default, the FASTA loader will use the first word (character string
  105. before the first space) as the name for your feature. If
  106. this does not uniquely identify your feature consider specifying a regular expression in the advanced section below.
  107. Additionally, you may import both a name and a unique name for each sequence using the advanced options.'),
  108. '#default_value' => 1
  109. );
  110. // Additional Options
  111. $form['additional'] = array(
  112. '#type' => 'fieldset',
  113. '#title' => t('Additional Options'),
  114. '#collapsible' => TRUE,
  115. '#collapsed' => TRUE
  116. );
  117. $form['additional']['re_help'] = array('#type' => 'item',
  118. '#value' => t('A regular expression is an advanced method for extracting
  119. information from a string of text. Your FASTA file may contain both a
  120. human-readable name and a unique name for each sequence. If you want
  121. to import both the name and unique name for all sequences, then you
  122. must provide regular expressions so that the loader knows how to
  123. separate them. Otherwise the name and uniquename will be the same.
  124. By default, this loader will use the first word in the definition
  125. lines of the FASTA file
  126. as the name or unique name of the feature.')
  127. );
  128. $form['additional']['re_name'] = array('#type' => 'textfield',
  129. '#title' => t('Regular expression for the name'),'#required' => FALSE,
  130. '#description' => t('Enter the regular expression that will extract the
  131. feature name from the FASTA definition line. For example, for a
  132. defintion line with a name and unique name separated by a bar \'|\' (>seqname|uniquename),
  133. the regular expression for the name would be, "^(.*?)\|.*$". All FASTA
  134. definition lines begin with the ">" symbol. You do not need to incldue
  135. this symbol in your regular expression.')
  136. );
  137. $form['additional']['re_uname'] = array('#type' => 'textfield',
  138. '#title' => t('Regular expression for the unique name'),'#required' => FALSE,
  139. '#description' => t('Enter the regular expression that will extract the
  140. feature name from the FASTA definition line. For example, for a
  141. defintion line with a name and unique name separated by a bar \'|\' (>seqname|uniquename),
  142. the regular expression for the unique name would be "^.*?\|(.*)$". All FASTA
  143. definition lines begin with the ">" symbol. You do not need to incldue
  144. this symbol in your regular expression.')
  145. );
  146. // Advanced database cross reference options.
  147. $form['additional']['db'] = array(
  148. '#type' => 'fieldset',
  149. '#title' => t('External Database Reference'),
  150. '#weight' => 6,
  151. '#collapsed' => TRUE
  152. );
  153. $form['additional']['db']['re_accession'] = array(
  154. '#type' => 'textfield',
  155. '#title' => t('Regular expression for the accession'),
  156. '#required' => FALSE,
  157. '#description' => t('Enter the regular expression that will extract the accession for the external database for each feature from the FASTA definition line.'),
  158. '#weight' => 2
  159. );
  160. // get the list of databases
  161. $sql = "SELECT * FROM {db} ORDER BY name";
  162. $db_rset = chado_query($sql);
  163. $dbs = array();
  164. $dbs[''] = '';
  165. while ($db = $db_rset->fetchObject()) {
  166. $dbs[$db->db_id] = "$db->name";
  167. }
  168. $form['additional']['db']['db_id'] = array(
  169. '#title' => t('External Database'),
  170. '#type' => t('select'),
  171. '#description' => t("Plese choose an external database for which these sequences have a cross reference."),
  172. '#required' => FALSE,
  173. '#options' => $dbs,
  174. '#weight' => 1
  175. );
  176. $form['additional']['relationship'] = array(
  177. '#type' => 'fieldset',
  178. '#title' => t('Relationships'),
  179. '#weight' => 6,'#collapsed' => TRUE
  180. );
  181. $rels = array();
  182. $rels[''] = '';
  183. $rels['part_of'] = 'part of';
  184. $rels['derives_from'] = 'produced by (derives from)';
  185. // Advanced references options
  186. $form['additional']['relationship']['rel_type'] = array(
  187. '#title' => t('Relationship Type'),
  188. '#type' => t('select'),
  189. '#description' => t("Use this option to create associations, or relationships between the
  190. features of this FASTA file and existing features in the database. For
  191. example, to associate a FASTA file of peptides to existing genes or transcript sequence,
  192. select the type 'produced by'. For a CDS sequences select the type 'part of'"),
  193. '#required' => FALSE,
  194. '#options' => $rels,
  195. '#weight' => 5
  196. );
  197. $form['additional']['relationship']['re_subject'] = array(
  198. '#type' => 'textfield',
  199. '#title' => t('Regular expression for the parent'),
  200. '#required' => FALSE,
  201. '#description' => t('Enter the regular expression that will extract the unique
  202. name needed to identify the existing sequence for which the
  203. relationship type selected above will apply.'),
  204. '#weight' => 6
  205. );
  206. $form['additional']['relationship']['parent_type'] = array(
  207. '#type' => 'textfield',
  208. '#title' => t('Parent Type'),
  209. '#required' => FALSE,
  210. '#description' => t('Please enter the Sequence Ontology term for the parent. For example
  211. if the FASTA file being loaded is a set of proteins that are
  212. products of genes, then use the SO term \'gene\' or \'transcript\' or equivalent. However,
  213. this type must match the type for already loaded features.'),
  214. '#weight' => 7
  215. );
  216. return $form;
  217. }
  218. /**
  219. * @see TripalImporter::formValidate()
  220. */
  221. public function formValidate($form, &$form_state) {
  222. $organism_id = $form_state['values']['organism_id'];
  223. $type = trim($form_state['values']['seqtype']);
  224. $method = trim($form_state['values']['method']);
  225. $match_type = trim($form_state['values']['match_type']);
  226. $re_name = trim($form_state['values']['re_name']);
  227. $re_uname = trim($form_state['values']['re_uname']);
  228. $re_accession = trim($form_state['values']['re_accession']);
  229. $db_id = $form_state['values']['db_id'];
  230. $rel_type = $form_state['values']['rel_type'];
  231. $re_subject = trim($form_state['values']['re_subject']);
  232. $parent_type = trim($form_state['values']['parent_type']);
  233. if ($method == 0) {
  234. $method = 'Insert only';
  235. }
  236. if ($method == 1) {
  237. $method = 'Update only';
  238. }
  239. if ($method == 2) {
  240. $method = 'Insert and update';
  241. }
  242. if ($match_type == 0) {
  243. $match_type = 'Name';
  244. }
  245. if ($match_type == 1) {
  246. $match_type = 'Unique name';
  247. }
  248. if ($re_name and !$re_uname and strcmp($match_type, 'Unique name') == 0) {
  249. form_set_error('re_uname', t("You must provide a regular expression to identify the sequence unique name"));
  250. }
  251. if (!$re_name and $re_uname and strcmp($match_type, 'Name') == 0) {
  252. form_set_error('re_name', t("You must provide a regular expression to identify the sequence name"));
  253. }
  254. // make sure if a relationship is specified that all fields are provided.
  255. if (($rel_type or $parent_type) and !$re_subject) {
  256. form_set_error('re_subject', t("Please provide a regular expression for the parent"));
  257. }
  258. if (($rel_type or $re_subject) and !$parent_type) {
  259. form_set_error('parent_type', t("Please provide a SO term for the parent"));
  260. }
  261. if (($parent_type or $re_subject) and !$rel_type) {
  262. form_set_error('rel_type', t("Please select a relationship type"));
  263. }
  264. // make sure if a database is specified that all fields are provided
  265. if ($db_id and !$re_accession) {
  266. form_set_error('re_accession', t("Please provide a regular expression for the accession"));
  267. }
  268. if ($re_accession and !$db_id) {
  269. form_set_error('db_id', t("Please select a database"));
  270. }
  271. // check to make sure the types exists
  272. $cvtermsql ="
  273. SELECT CVT.cvterm_id
  274. FROM {cvterm} CVT
  275. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  276. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  277. WHERE cv.name = :cvname and (CVT.name = :name or CVTS.synonym = :synonym)
  278. ";
  279. $cvterm = chado_query($cvtermsql,
  280. array(':cvname' => 'sequence',':name' => $type,':synonym' => $type))->fetchObject();
  281. if (!$cvterm) {
  282. 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."));
  283. }
  284. if ($rel_type) {
  285. $cvterm = chado_query($cvtermsql, array(':cvname' => 'sequence',':name' => $parent_type,
  286. ':synonym' => $parent_type
  287. ))->fetchObject();
  288. if (!$cvterm) {
  289. 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."));
  290. }
  291. }
  292. }
  293. /**
  294. * @see TripalImporter::run()
  295. */
  296. public function run() {
  297. $arguments = $this->arguments['run_args'];
  298. $file_path = $this->arguments['files'][0]['file_path'];
  299. $organism_id = $arguments['organism_id'];
  300. $type = $arguments['seqtype'];
  301. $method = $arguments['method'];
  302. $match_type = $arguments['match_type'];
  303. $re_name = $arguments['re_name'];
  304. $re_uname = $arguments['re_uname'];
  305. $re_accession = $arguments['re_accession'];
  306. $db_id = $arguments['db_id'];
  307. $rel_type = $arguments['rel_type'];
  308. $re_subject = $arguments['re_subject'];
  309. $parent_type = $arguments['parent_type'];
  310. $method = $arguments['method'];
  311. $analysis_id = $arguments['analysis_id'];
  312. $match_type = $arguments['match_type'];
  313. if ($method == 0) {
  314. $method = 'Insert only';
  315. }
  316. if ($method == 1) {
  317. $method = 'Update only';
  318. }
  319. if ($method == 2) {
  320. $method = 'Insert and update';
  321. }
  322. if ($match_type == 0) {
  323. $match_type = 'Name';
  324. }
  325. if ($match_type == 1) {
  326. $match_type = 'Unique name';
  327. }
  328. $this->loadFasta($file_path, $organism_id, $type, $re_name, $re_uname, $re_accession,
  329. $db_id, $rel_type, $re_subject, $parent_type, $method, $analysis_id,
  330. $match_type);
  331. }
  332. /**
  333. * Load a fasta file.
  334. *
  335. * @param $file_path
  336. * The full path to the fasta file to load.
  337. * @param $organism_id
  338. * The organism_id of the organism these features are from.
  339. * @param $type
  340. * The type of features contained in the fasta file.
  341. * @param $re_name
  342. * The regular expression to extract the feature.name from the fasta header.
  343. * @param $re_uname
  344. * The regular expression to extract the feature.uniquename from the fasta
  345. * header.
  346. * @param $re_accession
  347. * The regular expression to extract the accession of the feature.dbxref_id.
  348. * @param $db_id
  349. * The database ID of the above accession.
  350. * @param $rel_type
  351. * The type of relationship when creating a feature_relationship between
  352. * this feature (object) and an extracted subject.
  353. * @param $re_subject
  354. * The regular expression to extract the uniquename of the feature to be
  355. * the subject of the above specified relationship.
  356. * @param $parent_type
  357. * The type of the parent feature.
  358. * @param $method
  359. * The method of feature adding. (ie: 'Insert only', 'Update only',
  360. * 'Insert and update').
  361. * @param $analysis_id
  362. * The analysis_id to associate the features in this fasta file with.
  363. * @param $match_type
  364. * Whether to match existing features based on the 'Name' or 'Unique name'.
  365. */
  366. private function loadFasta($file_path, $organism_id, $type, $re_name, $re_uname, $re_accession,
  367. $db_id, $rel_type, $re_subject, $parent_type, $method, $analysis_id, $match_type) {
  368. // First get the type for this sequence.
  369. $cvtermsql = "
  370. SELECT CVT.cvterm_id
  371. FROM {cvterm} CVT
  372. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  373. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  374. WHERE cv.name = :cvname and (CVT.name = :name or CVTS.synonym = :synonym)
  375. ";
  376. $cvterm = chado_query($cvtermsql, array(':cvname' => 'sequence',':name' => $type,':synonym' => $type))->fetchObject();
  377. if (!$cvterm) {
  378. $this->logMessage("Cannot find the term type: '!type'", array('!type' => $type), TRIPAL_ERROR);
  379. return 0;
  380. }
  381. // Second, if there is a parent type then get that.
  382. $parentcvterm = NULL;
  383. if ($parent_type) {
  384. $parentcvterm = chado_query($cvtermsql, array(':cvname' => 'sequence', ':name' => $parent_type,':synonym' => $parent_type))->fetchObject();
  385. if (!$parentcvterm) {
  386. $this->logMessage("Cannot find the parent term type: '!type'",
  387. array('!type' => $parentcvterm), TRIPAL_ERROR);
  388. return 0;
  389. }
  390. }
  391. // Third, if there is a relationship type then get that.
  392. $relcvterm = NULL;
  393. if ($rel_type) {
  394. $relcvterm = chado_query($cvtermsql, array(':cvname' => 'sequence',':name' => $rel_type,':synonym' => $rel_type))->fetchObject();
  395. if (!$relcvterm) {
  396. $this->logMessage("Cannot find the relationship term type: '!type'",
  397. array('!type' => $relcvterm), TRIPAL_ERROR);
  398. return 0;
  399. }
  400. }
  401. // We need to get the table schema to make sure we don't overrun the
  402. // size of fields with what our regular expressions retrieve
  403. $feature_tbl = chado_get_schema('feature');
  404. $dbxref_tbl = chado_get_schema('dbxref');
  405. $this->logMessage(t("Step 1: Finding sequences..."));
  406. $filesize = filesize($file_path);
  407. $fh = fopen($file_path, 'r');
  408. if (!$fh) {
  409. throw new Exception(t("Cannot open file: !dfile", array('!dfile' => $file_path)));
  410. }
  411. $num_read = 0;
  412. // Iterate through the lines of the file. Keep a record for
  413. // where in the file each line is at for later import.
  414. $seqs = array();
  415. $num_seqs = 0;
  416. $prev_pos = 0;
  417. $set_start = FALSE;
  418. while ($line = fgets($fh)) {
  419. $num_read += strlen($line);
  420. // If we encounter a definition line then get the name, uniquename,
  421. // accession and relationship subject from the definition line.
  422. if (preg_match('/^>/', $line)) {
  423. // Remove the > symbol from the defline.
  424. $defline = preg_replace("/^>/", '', $line);
  425. // Get the feature name if a regular expression is provided.
  426. $name = "";
  427. if ($re_name) {
  428. if (!preg_match("/$re_name/", $defline, $matches)) {
  429. $this->logMessage("Regular expression for the feature name finds nothing. Line !line.",
  430. array('!line' => $i), TRIPAL_ERROR);
  431. }
  432. elseif (strlen($matches[1]) > $feature_tbl['fields']['name']['length']) {
  433. $this->logMessage("Regular expression retrieves a value too long for the feature name. Line !line.",
  434. array('!line' => $i), TRIPAL_WARNING);
  435. }
  436. else {
  437. $name = trim($matches[1]);
  438. }
  439. }
  440. // If the match_type is name and no regular expression was provided
  441. // then use the first word as the name, otherwise we don't set the name.
  442. elseif (strcmp($match_type, 'Name') == 0) {
  443. if (preg_match("/^\s*(.*?)[\s\|].*$/", $defline, $matches)) {
  444. if (strlen($matches[1]) > $feature_tbl['fields']['name']['length']) {
  445. $this->logMessage("Regular expression retrieves a feature name too long for the feature name. Line !line.",
  446. array('!line' => $i), TRIPAL_WARNING);
  447. }
  448. else {
  449. $name = trim($matches[1]);
  450. }
  451. }
  452. else {
  453. $this->logMessage("Cannot find a feature name. Line !line.", array('!line' => $i), TRIPAL_WARNING);
  454. }
  455. }
  456. // Get the feature uniquename if a regular expression is provided.
  457. $uname = "";
  458. if ($re_uname) {
  459. if (!preg_match("/$re_uname/", $defline, $matches)) {
  460. $this->logMessage("Regular expression for the feature unique name finds nothing. Line !line.",
  461. array('!line' => $i), TRIPAL_ERROR);
  462. }
  463. $uname = trim($matches[1]);
  464. }
  465. // If the match_type is name and no regular expression was provided
  466. // then use the first word as the name, otherwise, we don't set the
  467. // uniquename.
  468. elseif (strcmp($match_type, 'Unique name') == 0) {
  469. if (preg_match("/^\s*(.*?)[\s\|].*$/", $defline, $matches)) {
  470. $uname = trim($matches[1]);
  471. }
  472. else {
  473. $this->logMessage("Cannot find a feature unique name. Line !line.",
  474. array('!line' => $i), TRIPAL_ERROR);
  475. }
  476. }
  477. // Get the accession if a regular expression is provided.
  478. $accession = "";
  479. if (!empty($re_accession)) {
  480. preg_match("/$re_accession/", $defline, $matches);
  481. if (strlen($matches[1]) > $dbxref_tbl['fields']['accession']['length']) {
  482. tripal_report_error('trp-fasta', TRIPAL_WARNING, "WARNING: Regular expression retrieves an accession too long for the feature name. " .
  483. "Cannot add cross reference. Line %line.", array('%line' => $i
  484. ));
  485. }
  486. else {
  487. $accession = trim($matches[1]);
  488. }
  489. }
  490. // Get the relationship subject
  491. $subject = "";
  492. if (!empty($re_subject)) {
  493. preg_match("/$re_subject/", $line, $matches);
  494. $subject = trim($matches[1]);
  495. }
  496. // Add the details to the sequence.
  497. $seqs[$num_seqs] = array(
  498. 'name' => $name,
  499. 'uname' => $uname,
  500. 'accession' => $accession,
  501. 'subject' => $subject,
  502. 'seq_start' => ftell($fh)
  503. );
  504. $set_start = TRUE;
  505. // If this isn't the first sequence, then we want to specify where
  506. // the previous sequence ended.
  507. if ($num_seqs > 0) {
  508. $seqs[$num_seqs - 1]['seq_end'] = $prev_pos;
  509. }
  510. $num_seqs++;
  511. }
  512. // Keep the current file position so we can use it to set the sequence
  513. // ending position
  514. $prev_pos = ftell($fh);
  515. }
  516. // Set the end position for the last sequence.
  517. $seqs[$num_seqs - 1]['seq_end'] = $num_read - strlen($line);
  518. // Now that we know where the sequences are in the file we need to add them.
  519. $this->logMessage("Step 2: Importing sequences...");
  520. $this->logMessage("Found !num_seqs sequence(s).", array('!num_seqs' => $num_seqs));
  521. $this->setTotalItems($num_seqs);
  522. $this->setItemsHandled(0);
  523. for ($j = 0; $j < $num_seqs; $j++) {
  524. $seq = $seqs[$j];
  525. //$this->logMessage("Importing !seqname.", array('!seqname' => $seq['name']));
  526. $source = NULL;
  527. $this->loadFastaFeature($fh, $seq['name'], $seq['uname'], $db_id,
  528. $seq['accession'], $seq['subject'], $rel_type, $parent_type,
  529. $analysis_id, $organism_id, $cvterm, $source, $method, $re_name,
  530. $match_type, $parentcvterm, $relcvterm, $seq['seq_start'],
  531. $seq['seq_end']);
  532. $this->setItemsHandled($j);
  533. }
  534. fclose($fh);
  535. $this->setItemsHandled($num_seqs);
  536. }
  537. /**
  538. * A helper function for loadFasta() to load a single feature
  539. *
  540. * @ingroup fasta_loader
  541. */
  542. private function loadFastaFeature($fh, $name, $uname, $db_id, $accession, $parent,
  543. $rel_type, $parent_type, $analysis_id, $organism_id, $cvterm, $source, $method, $re_name,
  544. $match_type, $parentcvterm, $relcvterm, $seq_start, $seq_end) {
  545. // Check to see if this feature already exists if the match_type is 'Name'.
  546. if (strcmp($match_type, 'Name') == 0) {
  547. $values = array('organism_id' => $organism_id,'name' => $name,'type_id' => $cvterm->cvterm_id
  548. );
  549. $results = chado_select_record('feature', array('feature_id'
  550. ), $values);
  551. if (count($results) > 1) {
  552. $this->logMessage("Multiple features exist with the name '!name' of type '!type' for the organism. skipping",
  553. array('!name' => $name,'!type' => $type), TRIPAL_ERROR);
  554. return 0;
  555. }
  556. if (count($results) == 1) {
  557. $feature = $results[0];
  558. }
  559. }
  560. // Check if this feature already exists if the match_type is 'Unique Name'.
  561. if (strcmp($match_type, 'Unique name') == 0) {
  562. $values = array(
  563. 'organism_id' => $organism_id,
  564. 'uniquename' => $uname,
  565. 'type_id' => $cvterm->cvterm_id
  566. );
  567. $results = chado_select_record('feature', array('feature_id'), $values);
  568. if (count($results) > 1) {
  569. $this->logMessage("Multiple features exist with the name '!name' of type '!type' for the organism. skipping",
  570. array('!name' => $name,'!type' => $type), TRIPAL_WARNING);
  571. return 0;
  572. }
  573. if (count($results) == 1) {
  574. $feature = $results[0];
  575. }
  576. // If the feature exists but this is an "insert only" then skip.
  577. if (isset($feature) and (strcmp($method, 'Insert only') == 0)) {
  578. $this->logMessage("Feature already exists '!name' ('!uname') while matching on !type. Skipping insert.",
  579. array('!name' => $name,'!uname' => $uname,'!type' => drupal_strtolower($match_type)), TRIPAL_WARNING);
  580. return 0;
  581. }
  582. }
  583. // If we don't have a feature and we're doing an insert then do the insert.
  584. $inserted = 0;
  585. if (!isset($feature) and (strcmp($method, 'Insert only') == 0 or strcmp($method, 'Insert and update') == 0)) {
  586. // If we have a unique name but not a name then set them to be the same
  587. if (!$uname) {
  588. $uname = $name;
  589. }
  590. elseif (!$name) {
  591. $name = $uname;
  592. }
  593. // Insert the feature record.
  594. $values = array(
  595. 'organism_id' => $organism_id,
  596. 'name' => $name,
  597. 'uniquename' => $uname,
  598. 'type_id' => $cvterm->cvterm_id
  599. );
  600. $success = chado_insert_record('feature', $values);
  601. if (!$success) {
  602. $this->logMessage("Failed to insert feature '!name (!uname)'", array(
  603. '!name' => $name,'!uname' => $numane), TRIPAL_ERROR);
  604. return 0;
  605. }
  606. // now get the feature we just inserted
  607. $values = array(
  608. 'organism_id' => $organism_id,
  609. 'uniquename' => $uname,
  610. 'type_id' => $cvterm->cvterm_id
  611. );
  612. $results = chado_select_record('feature', array('feature_id'), $values);
  613. if (count($results) == 1) {
  614. $inserted = 1;
  615. $feature = $results[0];
  616. }
  617. else {
  618. $this->logMessage("Failed to retreive newly inserted feature '!name (!uname)'", array(
  619. '!name' => $name,'!uname' => $numane), TRIPAL_ERRORR);
  620. return 0;
  621. }
  622. // Add the residues for this feature
  623. $this->loadFastaResidues($fh, $feature->feature_id, $seq_start, $seq_end);
  624. }
  625. // if we don't have a feature and the user wants to do an update then fail
  626. if (!isset($feature) and (strcmp($method, 'Update only') == 0 or strcmp($method, 'Insert and update') == 0)) {
  627. $this->logMessage("Failed to find feature '!name' ('!uname') while matching on " . drupal_strtolower($match_type) . ".",
  628. array('!name' => $name,'!uname' => $uname), TRIPAL_ERROR);
  629. return 0;
  630. }
  631. // if we do have a feature and this is an update then proceed with the update
  632. if (isset($feature) and !$inserted and (strcmp($method, 'Update only') == 0 or strcmp($method, 'Insert and update') == 0)) {
  633. // if the user wants to match on the Name field
  634. if (strcmp($match_type, 'Name') == 0) {
  635. // if we're matching on the name but do not have a unique name then we
  636. // don't want to update the uniquename.
  637. $values = array();
  638. if ($uname) {
  639. // First check to make sure that by changing the unique name of this
  640. // feature that we won't conflict with another existing feature of
  641. // the same name
  642. $values = array(
  643. 'organism_id' => $organism_id,
  644. 'uniquename' => $uname,
  645. 'type_id' => $cvterm->cvterm_id
  646. );
  647. $results = chado_select_record('feature', array('feature_id'), $values);
  648. if (count($results) > 0) {
  649. $this->logMessage("Cannot update the feature '!name' with a uniquename of '!uname' and type of '!type' as it " .
  650. "conflicts with an existing feature with the same uniquename and type.",
  651. array('!name' => $name,'!uname' => $uname,'!type' => $type), TRIPAL_ERROR);
  652. return 0;
  653. }
  654. // the changes to the uniquename don't conflict so proceed with the update
  655. $values = array('uniquename' => $uname);
  656. $match = array(
  657. 'name' => $name,
  658. 'organism_id' => $organism_id,
  659. 'type_id' => $cvterm->cvterm_id
  660. );
  661. // perform the update
  662. $success = chado_update_record('feature', $match, $values);
  663. if (!$success) {
  664. $this->logMessage("Failed to update feature '!name' ('!name')",
  665. array('!name' => $name,'!uiname' => $uname), TRIPAL_ERROR);
  666. return 0;
  667. }
  668. }
  669. }
  670. // If the user wants to match on the unique name field.
  671. if (strcmp($match_type, 'Unique name') == 0) {
  672. // If we're matching on the uniquename and have a new name then
  673. // we want to update the name.
  674. $values = array();
  675. if ($name) {
  676. $values = array('name' => $name);
  677. $match = array(
  678. 'uniquename' => $uname,
  679. 'organism_id' => $organism_id,
  680. 'type_id' => $cvterm->cvterm_id
  681. );
  682. $success = chado_update_record('feature', $match, $values);
  683. if (!$success) {
  684. $this->logMessage("Failed to update feature '!name' ('!name')",
  685. array('!name' => $name,'!uiname' => $uname), TRIPAL_ERROR);
  686. return 0;
  687. }
  688. }
  689. }
  690. }
  691. // Update the residues for this feature
  692. $this->loadFastaResidues($fh, $feature->feature_id, $seq_start, $seq_end);
  693. // add in the analysis link
  694. if ($analysis_id) {
  695. // if the association doens't alredy exist then add one
  696. $values = array(
  697. 'analysis_id' => $analysis_id,
  698. 'feature_id' => $feature->feature_id
  699. );
  700. $results = chado_select_record('analysisfeature', array('analysisfeature_id'), $values);
  701. if (count($results) == 0) {
  702. $success = chado_insert_record('analysisfeature', $values);
  703. if (!$success) {
  704. $this->logMessage("Failed to associate analysis and feature '!name' ('!name')",
  705. array('!name' => $name,'!uname' => $uname), TRIPAL_ERROR);
  706. return 0;
  707. }
  708. }
  709. }
  710. // now add the database cross reference
  711. if ($db_id) {
  712. // check to see if this accession reference exists, if not add it
  713. $values = array(
  714. 'db_id' => $db_id,
  715. 'accession' => $accession
  716. );
  717. $results = chado_select_record('dbxref', array('dbxref_id'), $values);
  718. // if the accession doesn't exist then add it
  719. if (count($results) == 0) {
  720. $results = chado_insert_record('dbxref', $values);
  721. if (!$results) {
  722. $this->logMessage("Failed to add database accession '!accession'",
  723. array('!accession' => $accession), TRIPAL_ERROR);
  724. return 0;
  725. }
  726. $results = chado_select_record('dbxref', array('dbxref_id'), $values);
  727. if (count($results) == 1) {
  728. $dbxref = $results[0];
  729. }
  730. else {
  731. $this->logMessage("Failed to retreive newly inserted dbxref '!name (!uname)'",
  732. array('!name' => $name,'!uname' => $numane), TRIPAL_ERROR);
  733. return 0;
  734. }
  735. }
  736. else {
  737. $dbxref = $results[0];
  738. }
  739. // check to see if the feature dbxref record exists if not, then add it
  740. $values = array(
  741. 'feature_id' => $feature->feature_id,
  742. 'dbxref_id' => $dbxref->dbxref_id
  743. );
  744. $results = chado_select_record('feature_dbxref', array('feature_dbxref_id'), $values);
  745. if (count($results) == 0) {
  746. $success = chado_insert_record('feature_dbxref', $values);
  747. if (!$success) {
  748. $this->logMessage("Failed to add associate database accession '!accession' with feature",
  749. array('!accession' => $accession), TRIPAL_ERROR);
  750. return 0;
  751. }
  752. }
  753. }
  754. // now add in the relationship if one exists. If not, then add it
  755. if ($rel_type) {
  756. $values = array('organism_id' => $organism_id,'uniquename' => $parent, 'type_id' => $parentcvterm->cvterm_id);
  757. $results = chado_select_record('feature', array('feature_id'), $values);
  758. if (count($results) != 1) {
  759. $this->logMessage("Cannot find a unique feature for the parent '!parent' of type '!type' for the feature.",
  760. array('!parent' => $parent,'!type' => $parent_type), TRIPAL_ERROR);
  761. return 0;
  762. }
  763. $parent_feature = $results[0];
  764. // check to see if the relationship already exists if not then add it
  765. $values = array(
  766. 'subject_id' => $feature->feature_id,
  767. 'object_id' => $parent_feature->feature_id,
  768. 'type_id' => $relcvterm->cvterm_id
  769. );
  770. $results = chado_select_record('feature_relationship', array('feature_relationship_id'), $values);
  771. if (count($results) == 0) {
  772. $success = chado_insert_record('feature_relationship', $values);
  773. if (!$success) {
  774. $this->logMessage("Failed to add associate database accession '!accession' with feature",
  775. array('!accession' => $accession), TRIPAL_ERROR);
  776. return 0;
  777. }
  778. }
  779. }
  780. }
  781. /**
  782. * Adds the residues column to the feature.
  783. *
  784. * This function seeks to the proper location in the file for the sequence
  785. * and reads in chunks of sequence and appends them to the feature.residues
  786. * column in the database.
  787. *
  788. * @param $fh
  789. * @param $feature_id
  790. * @param $seq_start
  791. * @param $seq_end
  792. */
  793. private function loadFastaResidues($fh, $feature_id, $seq_start, $seq_end) {
  794. // First position the file at the beginning of the sequence
  795. fseek($fh, $seq_start, SEEK_SET);
  796. $chunk_size = 100000000;
  797. $chunk = '';
  798. $seqlen = ($seq_end - $seq_start);
  799. $num_read = 0;
  800. $total_seq_size = 0;
  801. // First, make sure we don't have a null in the residues
  802. $sql = "UPDATE {feature} SET residues = '' WHERE feature_id = :feature_id";
  803. chado_query($sql, array(':feature_id' => $feature_id));
  804. // Read in the lines until we reach the end of the sequence. Once we
  805. // get a specific bytes read then append the sequence to the one in the
  806. // database.
  807. $partial_seq_size = 0;
  808. $chunk_intv_read = 0;
  809. while ($line = fgets($fh)) {
  810. $num_read += strlen($line) + 1;
  811. $chunk_intv_read += strlen($line) + 1;
  812. $partial_seq_size += strlen($line);
  813. $chunk .= trim($line);
  814. // If we've read in enough of the sequence then append it to the database.
  815. if ($chunk_intv_read >= $chunk_size) {
  816. $sql = "
  817. UPDATE {feature}
  818. SET residues = residues || :chunk
  819. WHERE feature_id = :feature_id
  820. ";
  821. $success = chado_query($sql, array(':feature_id' => $feature_id,':chunk' => $chunk));
  822. if (!$success) {
  823. return FALSE;
  824. }
  825. $total_seq_size += strlen($chunk);
  826. $chunk = '';
  827. $chunk_intv_read = 0;
  828. }
  829. // If we've reached the end of the sequence then break out of the loop
  830. if (ftell($fh) == $seq_end) {
  831. break;
  832. }
  833. }
  834. // write the last bit of sequence if it remains
  835. if (strlen($chunk) > 0) {
  836. $sql = "
  837. UPDATE {feature}
  838. SET residues = residues || :chunk
  839. WHERE feature_id = :feature_id
  840. ";
  841. $success = chado_query($sql, array(':feature_id' => $feature_id,':chunk' => $chunk));
  842. if (!$success) {
  843. return FALSE;
  844. }
  845. $total_seq_size += $partial_seq_size;
  846. $partial_seq_size = 0;
  847. $chunk = '';
  848. $chunk_intv_read = 0;
  849. }
  850. // Now update the seqlen and md5checksum fields
  851. $sql = "UPDATE {feature} SET seqlen = char_length(residues), md5checksum = md5(residues) WHERE feature_id = :feature_id";
  852. chado_query($sql, array(':feature_id' => $feature_id));
  853. }
  854. }