FASTAImporter.inc 35 KB

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