FASTAImporter.inc 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  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. If no regular
  204. expression is provided, the parent unique name must be the
  205. same as the loaded feature name.'),
  206. '#weight' => 6
  207. );
  208. $form['additional']['relationship']['parent_type'] = array(
  209. '#type' => 'textfield',
  210. '#title' => t('Parent Type'),
  211. '#required' => FALSE,
  212. '#description' => t('Please enter the Sequence Ontology term for the parent. For example
  213. if the FASTA file being loaded is a set of proteins that are
  214. products of genes, then use the SO term \'gene\' or \'transcript\' or equivalent. However,
  215. this type must match the type for already loaded features.'),
  216. '#weight' => 7
  217. );
  218. return $form;
  219. }
  220. /**
  221. * @see TripalImporter::formValidate()
  222. */
  223. public function formValidate($form, &$form_state) {
  224. $organism_id = $form_state['values']['organism_id'];
  225. $type = trim($form_state['values']['seqtype']);
  226. $method = trim($form_state['values']['method']);
  227. $match_type = trim($form_state['values']['match_type']);
  228. $re_name = trim($form_state['values']['re_name']);
  229. $re_uname = trim($form_state['values']['re_uname']);
  230. $re_accession = trim($form_state['values']['re_accession']);
  231. $db_id = $form_state['values']['db_id'];
  232. $rel_type = $form_state['values']['rel_type'];
  233. $re_subject = trim($form_state['values']['re_subject']);
  234. $parent_type = trim($form_state['values']['parent_type']);
  235. if ($method == 0) {
  236. $method = 'Insert only';
  237. }
  238. if ($method == 1) {
  239. $method = 'Update only';
  240. }
  241. if ($method == 2) {
  242. $method = 'Insert and update';
  243. }
  244. if ($match_type == 0) {
  245. $match_type = 'Name';
  246. }
  247. if ($match_type == 1) {
  248. $match_type = 'Unique name';
  249. }
  250. if ($re_name and !$re_uname and strcmp($match_type, 'Unique name') == 0) {
  251. form_set_error('re_uname', t("You must provide a regular expression to identify the sequence unique name"));
  252. }
  253. if (!$re_name and $re_uname and strcmp($match_type, 'Name') == 0) {
  254. form_set_error('re_name', t("You must provide a regular expression to identify the sequence name"));
  255. }
  256. // make sure if a relationship is specified that all fields are provided.
  257. if (($rel_type or $re_subject) and !$parent_type) {
  258. form_set_error('parent_type', t("Please provide a SO term for the parent"));
  259. }
  260. if (($parent_type or $re_subject) and !$rel_type) {
  261. form_set_error('rel_type', t("Please select a relationship type"));
  262. }
  263. // make sure if a database is specified that all fields are provided
  264. if ($db_id and !$re_accession) {
  265. form_set_error('re_accession', t("Please provide a regular expression for the accession"));
  266. }
  267. if ($re_accession and !$db_id) {
  268. form_set_error('db_id', t("Please select a database"));
  269. }
  270. // check to make sure the types exists
  271. $cvtermsql ="
  272. SELECT CVT.cvterm_id
  273. FROM {cvterm} CVT
  274. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  275. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  276. WHERE cv.name = :cvname and (CVT.name = :name or CVTS.synonym = :synonym)
  277. ";
  278. $cvterm = chado_query($cvtermsql,
  279. array(':cvname' => 'sequence',':name' => $type,':synonym' => $type))->fetchObject();
  280. if (!$cvterm) {
  281. 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."));
  282. }
  283. if ($rel_type) {
  284. $cvterm = chado_query($cvtermsql, array(':cvname' => 'sequence',':name' => $parent_type,
  285. ':synonym' => $parent_type
  286. ))->fetchObject();
  287. if (!$cvterm) {
  288. 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."));
  289. }
  290. }
  291. }
  292. /**
  293. * @see TripalImporter::run()
  294. */
  295. public function run() {
  296. $arguments = $this->arguments['run_args'];
  297. $file_path = $this->arguments['files'][0]['file_path'];
  298. $organism_id = $arguments['organism_id'];
  299. $type = $arguments['seqtype'];
  300. $method = $arguments['method'];
  301. $match_type = $arguments['match_type'];
  302. $re_name = $arguments['re_name'];
  303. $re_uname = $arguments['re_uname'];
  304. $re_accession = $arguments['re_accession'];
  305. $db_id = $arguments['db_id'];
  306. $rel_type = $arguments['rel_type'];
  307. $re_subject = $arguments['re_subject'];
  308. $parent_type = $arguments['parent_type'];
  309. $method = $arguments['method'];
  310. $analysis_id = $arguments['analysis_id'];
  311. $match_type = $arguments['match_type'];
  312. if ($method == 0) {
  313. $method = 'Insert only';
  314. }
  315. if ($method == 1) {
  316. $method = 'Update only';
  317. }
  318. if ($method == 2) {
  319. $method = 'Insert and update';
  320. }
  321. if ($match_type == 0) {
  322. $match_type = 'Name';
  323. }
  324. if ($match_type == 1) {
  325. $match_type = 'Unique name';
  326. }
  327. $this->loadFasta($file_path, $organism_id, $type, $re_name, $re_uname, $re_accession,
  328. $db_id, $rel_type, $re_subject, $parent_type, $method, $analysis_id,
  329. $match_type);
  330. }
  331. /**
  332. * Load a fasta file.
  333. *
  334. * @param $file_path
  335. * The full path to the fasta file to load.
  336. * @param $organism_id
  337. * The organism_id of the organism these features are from.
  338. * @param $type
  339. * The type of features contained in the fasta file.
  340. * @param $re_name
  341. * The regular expression to extract the feature.name from the fasta header.
  342. * @param $re_uname
  343. * The regular expression to extract the feature.uniquename from the fasta
  344. * header.
  345. * @param $re_accession
  346. * The regular expression to extract the accession of the feature.dbxref_id.
  347. * @param $db_id
  348. * The database ID of the above accession.
  349. * @param $rel_type
  350. * The type of relationship when creating a feature_relationship between
  351. * this feature (object) and an extracted subject.
  352. * @param $re_subject
  353. * The regular expression to extract the uniquename of the feature to be
  354. * the subject of the above specified relationship.
  355. * @param $parent_type
  356. * The type of the parent feature.
  357. * @param $method
  358. * The method of feature adding. (ie: 'Insert only', 'Update only',
  359. * 'Insert and update').
  360. * @param $analysis_id
  361. * The analysis_id to associate the features in this fasta file with.
  362. * @param $match_type
  363. * Whether to match existing features based on the 'Name' or 'Unique name'.
  364. */
  365. private function loadFasta($file_path, $organism_id, $type, $re_name, $re_uname, $re_accession,
  366. $db_id, $rel_type, $re_subject, $parent_type, $method, $analysis_id, $match_type) {
  367. // First get the type for this sequence.
  368. $cvtermsql = "
  369. SELECT CVT.cvterm_id
  370. FROM {cvterm} CVT
  371. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  372. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  373. WHERE cv.name = :cvname and (CVT.name = :name or CVTS.synonym = :synonym)
  374. ";
  375. $cvterm = chado_query($cvtermsql, array(':cvname' => 'sequence',':name' => $type,':synonym' => $type))->fetchObject();
  376. if (!$cvterm) {
  377. $this->logMessage("Cannot find the term type: '!type'", array('!type' => $type), TRIPAL_ERROR);
  378. return 0;
  379. }
  380. // Second, if there is a parent type then get that.
  381. $parentcvterm = NULL;
  382. if ($parent_type) {
  383. $parentcvterm = chado_query($cvtermsql, array(':cvname' => 'sequence', ':name' => $parent_type,':synonym' => $parent_type))->fetchObject();
  384. if (!$parentcvterm) {
  385. $this->logMessage("Cannot find the parent term type: '!type'",
  386. array('!type' => $parentcvterm), TRIPAL_ERROR);
  387. return 0;
  388. }
  389. }
  390. // Third, if there is a relationship type then get that.
  391. $relcvterm = NULL;
  392. if ($rel_type) {
  393. $relcvterm = chado_query($cvtermsql, array(':cvname' => 'sequence',':name' => $rel_type,':synonym' => $rel_type))->fetchObject();
  394. if (!$relcvterm) {
  395. $this->logMessage("Cannot find the relationship term type: '!type'",
  396. array('!type' => $relcvterm), TRIPAL_ERROR);
  397. return 0;
  398. }
  399. }
  400. // We need to get the table schema to make sure we don't overrun the
  401. // size of fields with what our regular expressions retrieve
  402. $feature_tbl = chado_get_schema('feature');
  403. $dbxref_tbl = chado_get_schema('dbxref');
  404. $this->logMessage(t("Step 1: Finding sequences..."));
  405. $filesize = filesize($file_path);
  406. $fh = fopen($file_path, 'r');
  407. if (!$fh) {
  408. throw new Exception(t("Cannot open file: !dfile", array('!dfile' => $file_path)));
  409. }
  410. $num_read = 0;
  411. // Iterate through the lines of the file. Keep a record for
  412. // where in the file each line is at for later import.
  413. $seqs = array();
  414. $num_seqs = 0;
  415. $prev_pos = 0;
  416. $set_start = FALSE;
  417. while ($line = fgets($fh)) {
  418. $num_read += strlen($line);
  419. // If we encounter a definition line then get the name, uniquename,
  420. // accession and relationship subject from the definition line.
  421. if (preg_match('/^>/', $line)) {
  422. // Remove the > symbol from the defline.
  423. $defline = preg_replace("/^>/", '', $line);
  424. // Get the feature name if a regular expression is provided.
  425. $name = "";
  426. if ($re_name) {
  427. if (!preg_match("/$re_name/", $defline, $matches)) {
  428. $this->logMessage("Regular expression for the feature name finds nothing. Line !line.",
  429. array('!line' => $i), TRIPAL_ERROR);
  430. }
  431. elseif (strlen($matches[1]) > $feature_tbl['fields']['name']['length']) {
  432. $this->logMessage("Regular expression retrieves a value too long for the feature name. Line !line.",
  433. array('!line' => $i), TRIPAL_WARNING);
  434. }
  435. else {
  436. $name = trim($matches[1]);
  437. }
  438. }
  439. // If the match_type is name and no regular expression was provided
  440. // then use the first word as the name, otherwise we don't set the name.
  441. elseif (strcmp($match_type, 'Name') == 0) {
  442. if (preg_match("/^\s*(.*?)[\s\|].*$/", $defline, $matches)) {
  443. if (strlen($matches[1]) > $feature_tbl['fields']['name']['length']) {
  444. $this->logMessage("Regular expression retrieves a feature name too long for the feature name. Line !line.",
  445. array('!line' => $i), TRIPAL_WARNING);
  446. }
  447. else {
  448. $name = trim($matches[1]);
  449. }
  450. }
  451. else {
  452. $this->logMessage("Cannot find a feature name. Line !line.", array('!line' => $i), TRIPAL_WARNING);
  453. }
  454. }
  455. // Get the feature uniquename if a regular expression is provided.
  456. $uname = "";
  457. if ($re_uname) {
  458. if (!preg_match("/$re_uname/", $defline, $matches)) {
  459. $this->logMessage("Regular expression for the feature unique name finds nothing. Line !line.",
  460. array('!line' => $i), TRIPAL_ERROR);
  461. }
  462. $uname = trim($matches[1]);
  463. }
  464. // If the match_type is name and no regular expression was provided
  465. // then use the first word as the name, otherwise, we don't set the
  466. // uniquename.
  467. elseif (strcmp($match_type, 'Unique name') == 0) {
  468. if (preg_match("/^\s*(.*?)[\s\|].*$/", $defline, $matches)) {
  469. $uname = trim($matches[1]);
  470. }
  471. else {
  472. $this->logMessage("Cannot find a feature unique name. Line !line.",
  473. array('!line' => $i), TRIPAL_ERROR);
  474. }
  475. }
  476. // Get the accession if a regular expression is provided.
  477. $accession = "";
  478. if (!empty($re_accession)) {
  479. preg_match("/$re_accession/", $defline, $matches);
  480. if (strlen($matches[1]) > $dbxref_tbl['fields']['accession']['length']) {
  481. tripal_report_error('trp-fasta', TRIPAL_WARNING, "WARNING: Regular expression retrieves an accession too long for the feature name. " .
  482. "Cannot add cross reference. Line %line.", array('%line' => $i
  483. ));
  484. }
  485. else {
  486. $accession = trim($matches[1]);
  487. }
  488. }
  489. // Get the relationship subject
  490. $subject = $uname ? $uname : "";
  491. if (!empty($re_subject)) {
  492. preg_match("/$re_subject/", $line, $matches);
  493. $subject = trim($matches[1]);
  494. }
  495. // Add the details to the sequence.
  496. $seqs[$num_seqs] = array(
  497. 'name' => $name,
  498. 'uname' => $uname,
  499. 'accession' => $accession,
  500. 'subject' => $subject,
  501. 'seq_start' => ftell($fh)
  502. );
  503. $set_start = TRUE;
  504. // If this isn't the first sequence, then we want to specify where
  505. // the previous sequence ended.
  506. if ($num_seqs > 0) {
  507. $seqs[$num_seqs - 1]['seq_end'] = $prev_pos;
  508. }
  509. $num_seqs++;
  510. }
  511. // Keep the current file position so we can use it to set the sequence
  512. // ending position
  513. $prev_pos = ftell($fh);
  514. }
  515. // Set the end position for the last sequence.
  516. $seqs[$num_seqs - 1]['seq_end'] = $num_read - strlen($line);
  517. // Now that we know where the sequences are in the file we need to add them.
  518. $this->logMessage("Step 2: Importing sequences...");
  519. $this->logMessage("Found !num_seqs sequence(s).", array('!num_seqs' => $num_seqs));
  520. $this->setTotalItems($num_seqs);
  521. $this->setItemsHandled(0);
  522. for ($j = 0; $j < $num_seqs; $j++) {
  523. $seq = $seqs[$j];
  524. //$this->logMessage("Importing !seqname.", array('!seqname' => $seq['name']));
  525. $source = NULL;
  526. $this->loadFastaFeature($fh, $seq['name'], $seq['uname'], $db_id,
  527. $seq['accession'], $seq['subject'], $rel_type, $parent_type,
  528. $analysis_id, $organism_id, $cvterm, $source, $method, $re_name,
  529. $match_type, $parentcvterm, $relcvterm, $seq['seq_start'],
  530. $seq['seq_end']);
  531. $this->setItemsHandled($j);
  532. }
  533. fclose($fh);
  534. $this->setItemsHandled($num_seqs);
  535. }
  536. /**
  537. * A helper function for loadFasta() to load a single feature
  538. *
  539. * @ingroup fasta_loader
  540. */
  541. private function loadFastaFeature($fh, $name, $uname, $db_id, $accession, $parent,
  542. $rel_type, $parent_type, $analysis_id, $organism_id, $cvterm, $source, $method, $re_name,
  543. $match_type, $parentcvterm, $relcvterm, $seq_start, $seq_end) {
  544. // Check to see if this feature already exists if the match_type is 'Name'.
  545. if (strcmp($match_type, 'Name') == 0) {
  546. $values = array('organism_id' => $organism_id,'name' => $name,'type_id' => $cvterm->cvterm_id
  547. );
  548. $results = chado_select_record('feature', array('feature_id'
  549. ), $values);
  550. if (count($results) > 1) {
  551. $this->logMessage("Multiple features exist with the name '!name' of type '!type' for the organism. skipping",
  552. array('!name' => $name,'!type' => $type), TRIPAL_ERROR);
  553. return 0;
  554. }
  555. if (count($results) == 1) {
  556. $feature = $results[0];
  557. }
  558. }
  559. // Check if this feature already exists if the match_type is 'Unique Name'.
  560. if (strcmp($match_type, 'Unique name') == 0) {
  561. $values = array(
  562. 'organism_id' => $organism_id,
  563. 'uniquename' => $uname,
  564. 'type_id' => $cvterm->cvterm_id
  565. );
  566. $results = chado_select_record('feature', array('feature_id'), $values);
  567. if (count($results) > 1) {
  568. $this->logMessage("Multiple features exist with the name '!name' of type '!type' for the organism. skipping",
  569. array('!name' => $name,'!type' => $type), TRIPAL_WARNING);
  570. return 0;
  571. }
  572. if (count($results) == 1) {
  573. $feature = $results[0];
  574. }
  575. // If the feature exists but this is an "insert only" then skip.
  576. if (isset($feature) and (strcmp($method, 'Insert only') == 0)) {
  577. $this->logMessage("Feature already exists '!name' ('!uname') while matching on !type. Skipping insert.",
  578. array('!name' => $name,'!uname' => $uname,'!type' => drupal_strtolower($match_type)), TRIPAL_WARNING);
  579. return 0;
  580. }
  581. }
  582. // If we don't have a feature and we're doing an insert then do the insert.
  583. $inserted = 0;
  584. if (!isset($feature) and (strcmp($method, 'Insert only') == 0 or strcmp($method, 'Insert and update') == 0)) {
  585. // If we have a unique name but not a name then set them to be the same
  586. if (!$uname) {
  587. $uname = $name;
  588. }
  589. elseif (!$name) {
  590. $name = $uname;
  591. }
  592. // Insert the feature record.
  593. $values = array(
  594. 'organism_id' => $organism_id,
  595. 'name' => $name,
  596. 'uniquename' => $uname,
  597. 'type_id' => $cvterm->cvterm_id
  598. );
  599. $success = chado_insert_record('feature', $values);
  600. if (!$success) {
  601. $this->logMessage("Failed to insert feature '!name (!uname)'", array(
  602. '!name' => $name,'!uname' => $numane), TRIPAL_ERROR);
  603. return 0;
  604. }
  605. // now get the feature we just inserted
  606. $values = array(
  607. 'organism_id' => $organism_id,
  608. 'uniquename' => $uname,
  609. 'type_id' => $cvterm->cvterm_id
  610. );
  611. $results = chado_select_record('feature', array('feature_id'), $values);
  612. if (count($results) == 1) {
  613. $inserted = 1;
  614. $feature = $results[0];
  615. }
  616. else {
  617. $this->logMessage("Failed to retreive newly inserted feature '!name (!uname)'", array(
  618. '!name' => $name,'!uname' => $numane), TRIPAL_ERRORR);
  619. return 0;
  620. }
  621. // Add the residues for this feature
  622. $this->loadFastaResidues($fh, $feature->feature_id, $seq_start, $seq_end);
  623. }
  624. // if we don't have a feature and the user wants to do an update then fail
  625. if (!isset($feature) and (strcmp($method, 'Update only') == 0 or strcmp($method, 'Insert and update') == 0)) {
  626. $this->logMessage("Failed to find feature '!name' ('!uname') while matching on " . drupal_strtolower($match_type) . ".",
  627. array('!name' => $name,'!uname' => $uname), TRIPAL_ERROR);
  628. return 0;
  629. }
  630. // if we do have a feature and this is an update then proceed with the update
  631. if (isset($feature) and !$inserted and (strcmp($method, 'Update only') == 0 or strcmp($method, 'Insert and update') == 0)) {
  632. // if the user wants to match on the Name field
  633. if (strcmp($match_type, 'Name') == 0) {
  634. // if we're matching on the name but do not have a unique name then we
  635. // don't want to update the uniquename.
  636. $values = array();
  637. if ($uname) {
  638. // First check to make sure that by changing the unique name of this
  639. // feature that we won't conflict with another existing feature of
  640. // the same name
  641. $values = array(
  642. 'organism_id' => $organism_id,
  643. 'uniquename' => $uname,
  644. 'type_id' => $cvterm->cvterm_id
  645. );
  646. $results = chado_select_record('feature', array('feature_id'), $values);
  647. if (count($results) > 0) {
  648. $this->logMessage("Cannot update the feature '!name' with a uniquename of '!uname' and type of '!type' as it " .
  649. "conflicts with an existing feature with the same uniquename and type.",
  650. array('!name' => $name,'!uname' => $uname,'!type' => $type), TRIPAL_ERROR);
  651. return 0;
  652. }
  653. // the changes to the uniquename don't conflict so proceed with the update
  654. $values = array('uniquename' => $uname);
  655. $match = array(
  656. 'name' => $name,
  657. 'organism_id' => $organism_id,
  658. 'type_id' => $cvterm->cvterm_id
  659. );
  660. // perform the update
  661. $success = chado_update_record('feature', $match, $values);
  662. if (!$success) {
  663. $this->logMessage("Failed to update feature '!name' ('!name')",
  664. array('!name' => $name,'!uiname' => $uname), TRIPAL_ERROR);
  665. return 0;
  666. }
  667. }
  668. }
  669. // If the user wants to match on the unique name field.
  670. if (strcmp($match_type, 'Unique name') == 0) {
  671. // If we're matching on the uniquename and have a new name then
  672. // we want to update the name.
  673. $values = array();
  674. if ($name) {
  675. $values = array('name' => $name);
  676. $match = array(
  677. 'uniquename' => $uname,
  678. 'organism_id' => $organism_id,
  679. 'type_id' => $cvterm->cvterm_id
  680. );
  681. $success = chado_update_record('feature', $match, $values);
  682. if (!$success) {
  683. $this->logMessage("Failed to update feature '!name' ('!name')",
  684. array('!name' => $name,'!uiname' => $uname), TRIPAL_ERROR);
  685. return 0;
  686. }
  687. }
  688. }
  689. }
  690. // Update the residues for this feature
  691. $this->loadFastaResidues($fh, $feature->feature_id, $seq_start, $seq_end);
  692. // add in the analysis link
  693. if ($analysis_id) {
  694. // if the association doens't alredy exist then add one
  695. $values = array(
  696. 'analysis_id' => $analysis_id,
  697. 'feature_id' => $feature->feature_id
  698. );
  699. $results = chado_select_record('analysisfeature', array('analysisfeature_id'), $values);
  700. if (count($results) == 0) {
  701. $success = chado_insert_record('analysisfeature', $values);
  702. if (!$success) {
  703. $this->logMessage("Failed to associate analysis and feature '!name' ('!name')",
  704. array('!name' => $name,'!uname' => $uname), TRIPAL_ERROR);
  705. return 0;
  706. }
  707. }
  708. }
  709. // now add the database cross reference
  710. if ($db_id) {
  711. // check to see if this accession reference exists, if not add it
  712. $values = array(
  713. 'db_id' => $db_id,
  714. 'accession' => $accession
  715. );
  716. $results = chado_select_record('dbxref', array('dbxref_id'), $values);
  717. // if the accession doesn't exist then add it
  718. if (count($results) == 0) {
  719. $results = chado_insert_record('dbxref', $values);
  720. if (!$results) {
  721. $this->logMessage("Failed to add database accession '!accession'",
  722. array('!accession' => $accession), TRIPAL_ERROR);
  723. return 0;
  724. }
  725. $results = chado_select_record('dbxref', array('dbxref_id'), $values);
  726. if (count($results) == 1) {
  727. $dbxref = $results[0];
  728. }
  729. else {
  730. $this->logMessage("Failed to retreive newly inserted dbxref '!name (!uname)'",
  731. array('!name' => $name,'!uname' => $numane), TRIPAL_ERROR);
  732. return 0;
  733. }
  734. }
  735. else {
  736. $dbxref = $results[0];
  737. }
  738. // check to see if the feature dbxref record exists if not, then add it
  739. $values = array(
  740. 'feature_id' => $feature->feature_id,
  741. 'dbxref_id' => $dbxref->dbxref_id
  742. );
  743. $results = chado_select_record('feature_dbxref', array('feature_dbxref_id'), $values);
  744. if (count($results) == 0) {
  745. $success = chado_insert_record('feature_dbxref', $values);
  746. if (!$success) {
  747. $this->logMessage("Failed to add associate database accession '!accession' with feature",
  748. array('!accession' => $accession), TRIPAL_ERROR);
  749. return 0;
  750. }
  751. }
  752. }
  753. // now add in the relationship if one exists. If not, then add it
  754. if ($rel_type) {
  755. $values = array('organism_id' => $organism_id,'uniquename' => $parent, 'type_id' => $parentcvterm->cvterm_id);
  756. $results = chado_select_record('feature', array('feature_id'), $values);
  757. if (count($results) != 1) {
  758. $this->logMessage("Cannot find a unique feature for the parent '!parent' of type '!type' for the feature.",
  759. array('!parent' => $parent,'!type' => $parent_type), TRIPAL_ERROR);
  760. return 0;
  761. }
  762. $parent_feature = $results[0];
  763. // check to see if the relationship already exists if not then add it
  764. $values = array(
  765. 'subject_id' => $feature->feature_id,
  766. 'object_id' => $parent_feature->feature_id,
  767. 'type_id' => $relcvterm->cvterm_id
  768. );
  769. $results = chado_select_record('feature_relationship', array('feature_relationship_id'), $values);
  770. if (count($results) == 0) {
  771. $success = chado_insert_record('feature_relationship', $values);
  772. if (!$success) {
  773. $this->logMessage("Failed to add associate database accession '!accession' with feature",
  774. array('!accession' => $accession), TRIPAL_ERROR);
  775. return 0;
  776. }
  777. }
  778. }
  779. }
  780. /**
  781. * Adds the residues column to the feature.
  782. *
  783. * This function seeks to the proper location in the file for the sequence
  784. * and reads in chunks of sequence and appends them to the feature.residues
  785. * column in the database.
  786. *
  787. * @param $fh
  788. * @param $feature_id
  789. * @param $seq_start
  790. * @param $seq_end
  791. */
  792. private function loadFastaResidues($fh, $feature_id, $seq_start, $seq_end) {
  793. // First position the file at the beginning of the sequence
  794. fseek($fh, $seq_start, SEEK_SET);
  795. $chunk_size = 100000000;
  796. $chunk = '';
  797. $seqlen = ($seq_end - $seq_start);
  798. $num_read = 0;
  799. $total_seq_size = 0;
  800. // First, make sure we don't have a null in the residues
  801. $sql = "UPDATE {feature} SET residues = '' WHERE feature_id = :feature_id";
  802. chado_query($sql, array(':feature_id' => $feature_id));
  803. // Read in the lines until we reach the end of the sequence. Once we
  804. // get a specific bytes read then append the sequence to the one in the
  805. // database.
  806. $partial_seq_size = 0;
  807. $chunk_intv_read = 0;
  808. while ($line = fgets($fh)) {
  809. $num_read += strlen($line) + 1;
  810. $chunk_intv_read += strlen($line) + 1;
  811. $partial_seq_size += strlen($line);
  812. $chunk .= trim($line);
  813. // If we've read in enough of the sequence then append it to the database.
  814. if ($chunk_intv_read >= $chunk_size) {
  815. $sql = "
  816. UPDATE {feature}
  817. SET residues = residues || :chunk
  818. WHERE feature_id = :feature_id
  819. ";
  820. $success = chado_query($sql, array(':feature_id' => $feature_id,':chunk' => $chunk));
  821. if (!$success) {
  822. return FALSE;
  823. }
  824. $total_seq_size += strlen($chunk);
  825. $chunk = '';
  826. $chunk_intv_read = 0;
  827. }
  828. // If we've reached the end of the sequence then break out of the loop
  829. if (ftell($fh) == $seq_end) {
  830. break;
  831. }
  832. }
  833. // write the last bit of sequence if it remains
  834. if (strlen($chunk) > 0) {
  835. $sql = "
  836. UPDATE {feature}
  837. SET residues = residues || :chunk
  838. WHERE feature_id = :feature_id
  839. ";
  840. $success = chado_query($sql, array(':feature_id' => $feature_id,':chunk' => $chunk));
  841. if (!$success) {
  842. return FALSE;
  843. }
  844. $total_seq_size += $partial_seq_size;
  845. $partial_seq_size = 0;
  846. $chunk = '';
  847. $chunk_intv_read = 0;
  848. }
  849. // Now update the seqlen and md5checksum fields
  850. $sql = "UPDATE {feature} SET seqlen = char_length(residues), md5checksum = md5(residues) WHERE feature_id = :feature_id";
  851. chado_query($sql, array(':feature_id' => $feature_id));
  852. }
  853. }