FASTAImporter.inc 37 KB

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