GFF3Importer.inc 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190
  1. <?php
  2. class GFF3Importer 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 GFF3 File 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_gff3_loader';
  13. /**
  14. * A brief description for this loader. This description will be
  15. * presented to the site user.
  16. */
  17. public static $description = 'Import a GFF3 file into Chado';
  18. /**
  19. * An array containing the extensions of allowed file types.
  20. */
  21. public static $file_types = array('gff', 'gff3');
  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 GFF3 file.';
  27. /**
  28. * The title that should appear above the upload button.
  29. */
  30. public static $upload_title = 'GFF3 File';
  31. /**
  32. * Text that should appear on the button at the bottom of the importer
  33. * form.
  34. */
  35. public static $button_text = 'Import GFF3 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. // Advanced Options
  56. $form['advanced'] = array(
  57. '#type' => 'fieldset',
  58. '#title' => t('Additional Options'),
  59. '#collapsible' => TRUE,
  60. '#collapsed' => TRUE,
  61. );
  62. $form['advanced']['line_number']= array(
  63. '#type' => 'textfield',
  64. '#title' => t('Start Line Number'),
  65. '#description' => t('Enter the line number in the GFF file where you would like to begin processing. The
  66. first line is line number 1. This option is useful for examining loading problems with large GFF files.'),
  67. '#size' => 10,
  68. );
  69. $form['advanced']['landmark_type'] = array(
  70. '#title' => t('Landmark Type'),
  71. '#type' => t('textfield'),
  72. '#description' => t("Optional. Use this field to specify a Sequence Ontology type
  73. for the landmark sequences in the GFF fie (e.g. 'chromosome'). If the GFF file
  74. contains a '##sequence-region' line that describes the landmark sequences to
  75. which all others are aligned and a type is provided here then the features
  76. will be created if they do not already exist. If they do exist then this
  77. field is not used."),
  78. );
  79. $form['advanced']['alt_id_attr'] = array(
  80. '#title' => t('ID Attribute'),
  81. '#type' => t('textfield'),
  82. '#description' => t("Optional. Sometimes lines in the GFF file are missing the
  83. required ID attribute that specifies the unique name of the feature, but there
  84. may be another attribute that can uniquely identify the feature. If so,
  85. you may specify the name of the attribute to use for the name."),
  86. );
  87. $form['advanced']['protein_names'] = array(
  88. '#type' => 'fieldset',
  89. '#title' => t('Protein Names'),
  90. '#collapsible' => TRUE,
  91. '#collapsed' => FALSE,
  92. '#weight' => 5,
  93. );
  94. $form['advanced']['protein_names']['re_help'] = array(
  95. '#type' => 'item',
  96. '#markup' => t('A regular expression is an advanced method for extracting information from a string of text.
  97. If your GFF3 file does not contain polypeptide (or protein) features, but contains CDS features, proteins will be automatically created.
  98. By default the loader will give each protein a name based on the name of the corresponding mRNA followed by the "-protein" suffix.
  99. If you want to customize the name of the created protein, you can use the following regex.')
  100. );
  101. $form['advanced']['protein_names']['re_mrna'] = array(
  102. '#type' => 'textfield',
  103. '#title' => t('Regular expression for the mRNA name'),
  104. '#required' => FALSE,
  105. '#description' => t('Enter the regular expression that will extract portions of
  106. the mRNA unique name. For example, for a
  107. mRNA with a unique name finishing by -RX (e.g. SPECIES0000001-RA),
  108. the regular expression would be, "^(.*?)-R([A-Z]+)$".')
  109. );
  110. $form['advanced']['protein_names']['re_protein'] = array(
  111. '#type' => 'textfield',
  112. '#title' => t('Replacement string for the protein name'),
  113. '#required' => FALSE,
  114. '#description' => t('Enter the replacement string that will be used to create
  115. the protein name based on the mRNA regular expression. For example, for a
  116. mRNA regular expression "^(.*?)-R()[A-Z]+)$", the corresponding protein regular
  117. expression would be "$1-P$2".')
  118. );
  119. $form['advanced']['use_transaction']= array(
  120. '#type' => 'checkbox',
  121. '#title' => t('Use a transaction'),
  122. '#required' => FALSE,
  123. '#description' => t('Use a database transaction when loading the GFF file. If an error occurs
  124. the entire datset loaded prior to the failure will be rolled back and will not be available
  125. in the database. If this option is unchecked and failure occurs all records up to the point
  126. of failure will be present in the database.'),
  127. '#default_value' => 1,
  128. );
  129. $form['advanced']['add_only']= array(
  130. '#type' => 'checkbox',
  131. '#title' => t('Import only new features'),
  132. '#required' => FALSE,
  133. '#description' => t('The job will skip features in the GFF file that already
  134. exist in the database and import only new features.'),
  135. );
  136. $form['advanced']['update']= array(
  137. '#type' => 'checkbox',
  138. '#title' => t('Import all and update'),
  139. '#required' => FALSE,
  140. '#default_value' => 'checked',
  141. '#description' => t('Existing features will be updated and new features will be added. Attributes
  142. for a feature that are not present in the GFF but which are present in the
  143. database will not be altered.'),
  144. '#default_value' => 1,
  145. );
  146. // SPF: there are bugs in refreshing and removing features. The bugs arise
  147. // if a feature in the GFF does not have a uniquename. GenSAS will auto
  148. // generate this uniquename and it will not be the same as a previous
  149. // load because it uses the date. This causes orphaned CDS/exons, UTRs
  150. // to be left behind during a delete or refresh. So, the short term
  151. // fix is to remove these options.
  152. // $form['import_options']['refresh']= array(
  153. // '#type' => 'checkbox',
  154. // '#title' => t('Import all and replace'),
  155. // '#required' => FALSE,
  156. // '#description' => t('Existing features will be updated and feature properties not
  157. // present in the GFF file will be removed.'),
  158. // );
  159. // $form['import_options']['remove']= array(
  160. // '#type' => 'checkbox',
  161. // '#title' => t('Delete features'),
  162. // '#required' => FALSE,
  163. // '#description' => t('Features present in the GFF file that exist in the database
  164. // will be removed rather than imported'),
  165. // );
  166. $form['advanced']['create_organism']= array(
  167. '#type' => 'checkbox',
  168. '#title' => t('Create organism'),
  169. '#required' => FALSE,
  170. '#description' => t('The Tripal GFF loader supports the "organism" attribute. This allows features of a
  171. different organism to be aligned to the landmark sequence of another species. The format of the
  172. attribute is "organism=[genus]:[species]", where [genus] is the organism\'s genus and [species] is the
  173. species name. Check this box to automatically add the organism to the database if it does not already exists.
  174. Otherwise lines with an oraganism attribute where the organism is not present in the database will be skipped.'),
  175. );
  176. $form['advanced']['targets'] = array(
  177. '#type' => 'fieldset',
  178. '#title' => t('Targets'),
  179. '#collapsible' => TRUE,
  180. '#collapsed' => FALSE,
  181. '#weight' => 1,
  182. );
  183. $form['advanced']['targets']['adesc'] = array(
  184. '#markup' => t("When alignments are represented in the GFF file (e.g. such as
  185. alignments of cDNA sequences to a whole genome, or blast matches), they are
  186. represented using two feature types: 'match' (or cDNA_match, EST_match, etc.)
  187. and 'match_part'. These features may also have a 'Target' attribute to
  188. specify the sequence that is being aligned.
  189. However, the organism to which the aligned sequence belongs may not be present in the
  190. GFF file. Here you can specify the organism and feature type of the target sequences.
  191. The options here will apply to all targets unless the organism and type are explicity
  192. set in the GFF file using the 'target_organism' and 'target_type' attributes."),
  193. );
  194. $form['advanced']['targets']['target_organism_id'] = array(
  195. '#title' => t('Target Organism'),
  196. '#type' => t('select'),
  197. '#description' => t("Optional. Choose the organism to which target sequences belong.
  198. Select this only if target sequences belong to a different organism than the
  199. one specified above. And only choose an organism here if all of the target sequences
  200. belong to the same species. If the targets in the GFF file belong to multiple
  201. different species then the organism must be specified using the 'target_organism=genus:species'
  202. attribute in the GFF file."),
  203. '#options' => $organisms,
  204. );
  205. $form['advanced']['targets']['target_type'] = array(
  206. '#title' => t('Target Type'),
  207. '#type' => t('textfield'),
  208. '#description' => t("Optional. If the unique name for a target sequence is not unique (e.g. a protein
  209. and an mRNA have the same name) then you must specify the type for all targets in the GFF file. If
  210. the targets are of different types then the type must be specified using the 'target_type=type' attribute
  211. in the GFF file. This must be a valid Sequence Ontology (SO) term."),
  212. );
  213. $form['advanced']['targets']['create_target']= array(
  214. '#type' => 'checkbox',
  215. '#title' => t('Create Target'),
  216. '#required' => FALSE,
  217. '#description' => t("If the target feature cannot be found, create one using the organism and type specified above, or
  218. using the 'target_organism' and 'target_type' fields specified in the GFF file. Values specified in the
  219. GFF file take precedence over those specified above."),
  220. );
  221. return $form;
  222. }
  223. /**
  224. * @see TripalImporter::formValidate()
  225. */
  226. public function formValidate($form, &$form_state) {
  227. $organism_id = $form_state['values']['organism_id'];
  228. $target_organism_id = $form_state['values']['target_organism_id'];
  229. $target_type = trim($form_state['values']['target_type']);
  230. $create_target = $form_state['values']['create_target'];
  231. $create_organism = $form_state['values']['create_organism'];
  232. $add_only = $form_state['values']['add_only'];
  233. $update = $form_state['values']['update'];
  234. $refresh = 0; //$form_state['values']['refresh'];
  235. $remove = 0; //$form_state['values']['remove'];
  236. $use_transaction = $form_state['values']['use_transaction'];
  237. $line_number = trim($form_state['values']['line_number']);
  238. $landmark_type = trim($form_state['values']['landmark_type']);
  239. $alt_id_attr = trim($form_state['values']['alt_id_attr']);
  240. $re_mrna = trim($form_state['values']['re_mrna']);
  241. $re_protein = trim($form_state['values']['re_protein']);
  242. // @coder-ignore: there are no functions being called here
  243. if (($add_only AND ($update OR $refresh OR $remove)) OR
  244. ($update AND ($add_only OR $refresh OR $remove)) OR
  245. ($refresh AND ($update OR $add_only OR $remove)) OR
  246. ($remove AND ($update OR $refresh OR $add_only))) {
  247. form_set_error('add_only', t("Please select only one checkbox from the import options section"));
  248. }
  249. if ($line_number and !is_numeric($line_number) or $line_number < 0) {
  250. form_set_error('line_number', t("Please provide an integer line number greater than zero."));
  251. }
  252. if (!($re_mrna and $re_protein) and ($re_mrna or $re_protein)) {
  253. form_set_error('re_uname', t("You must provide both a regular expression for mRNA and a replacement string for protein"));
  254. }
  255. // check the regular expression to make sure it is valid
  256. set_error_handler(function() {}, E_WARNING);
  257. $result_re = preg_match("/" . $re_mrna . "/", null);
  258. $result = preg_replace("/" . $re_mrna . "/", $re_protein, null);
  259. restore_error_handler();
  260. if ($result_re === FALSE) {
  261. form_set_error('re_mrna', 'Invalid regular expression.');
  262. } else if ($result === FALSE) {
  263. form_set_error('re_protein', 'Invalid replacement string.');
  264. }
  265. }
  266. /**
  267. * @see TripalImporter::run()
  268. */
  269. public function run() {
  270. $arguments = $this->arguments['run_args'];
  271. $file_path = $this->arguments['files'][0]['file_path'];
  272. $organism_id = $arguments['organism_id'];
  273. $analysis_id = $arguments['analysis_id'];
  274. $add_only = $arguments['add_only'];
  275. $update = $arguments['update'];
  276. $refresh = FALSE;
  277. $remove = FALSE;
  278. $use_transaction = $arguments['use_transaction'];
  279. $target_organism_id = $arguments['target_organism_id'];
  280. $target_type = $arguments['target_type'];
  281. $create_target = $arguments['create_target'];
  282. $start_line = $arguments['line_number'];
  283. $landmark_type = $arguments['landmark_type'];
  284. $alt_id_attr = $arguments['alt_id_attr'];
  285. $create_organism = $arguments['create_organism'];
  286. $re_mrna = $arguments['re_mrna'];
  287. $re_protein = $arguments['re_protein'];
  288. $this->loadGFF3($file_path, $organism_id, $analysis_id,
  289. $add_only, $update, $refresh, $remove, $use_transaction,
  290. $target_organism_id, $target_type, $create_target,
  291. $start_line, $landmark_type, $alt_id_attr, $create_organism,
  292. $re_mrna, $re_protein);
  293. }
  294. /**
  295. * Actually load a GFF3 file. This is the function called by tripal jobs
  296. *
  297. * @param $gff_file
  298. * The full path to the GFF file on the filesystem
  299. * @param $organism_id
  300. * The organism_id of the organism to which the features in the GFF belong
  301. * @param $analysis_id
  302. * The anlaysis_id of the analysis from which the features in the GFF were generated
  303. * @param $add_only
  304. * Set to 1 if feature should be added only. In the case where a feature
  305. * already exists, it will not be updated. Default is 0
  306. * @param $update
  307. * Set to 1 to update existing features. New features will be added. Attributes
  308. * for a feature that are not present in the GFF but which are present in the
  309. * database will not be altered. Default is 1
  310. * @param $refresh
  311. * Set to 1 to update existing features. New features will be added. Attributes
  312. * for a feature that are not present in the GFF but which are present in the
  313. * database will be removed. Default is 0
  314. * @param $remove
  315. * Set to 1 to remove features present in the GFF file that exist in the database.
  316. * Default is 0.
  317. * @param $use_transaction
  318. * Set to 1 to use a transaction when loading the GFF. Any failure during
  319. * loading will result in the rollback of any changes. Default is 1.
  320. * @param $target_organism_id
  321. * If the GFF file contains a 'Target' attribute then the feature and the
  322. * target will have an alignment created, but to find the proper target
  323. * feature the target organism must also be known. If different from the
  324. * organism specified for the GFF file, then use this argument to specify
  325. * the target organism. Only use this argument if all target sequences belong
  326. * to the same species. If the targets in the GFF file belong to multiple
  327. * different species then the organism must be specified using the
  328. * 'target_organism=genus:species' attribute in the GFF file. Default is NULL.
  329. * @param $target_type
  330. * If the GFF file contains a 'Target' attribute then the feature and the
  331. * target will have an alignment created, but to find the proper target
  332. * feature the target organism must also be known. This can be used to
  333. * specify the target feature type to help with identification of the target
  334. * feature. Only use this argument if all target sequences types are the same.
  335. * If the targets are of different types then the type must be specified using
  336. * the 'target_type=type' attribute in the GFF file. This must be a valid
  337. * Sequence Ontology (SO) term. Default is NULL
  338. * @param $create_target
  339. * Set to 1 to create the target feature if it cannot be found in the
  340. * database. Default is 0
  341. * @param $start_line
  342. * Set this to the line in the GFF file where importing should start. This
  343. * is useful for testing and debugging GFF files that may have problems and
  344. * you want to start at a particular line to speed testing. Default = 1
  345. * @param $landmark_type
  346. * Use this argument to specify a Sequence Ontology term name for the landmark
  347. * sequences in the GFF fie (e.g. 'chromosome'), if the GFF file contains a
  348. * '##sequence-region' line that describes the landmark sequences. Default = ''
  349. * @param $alt_id_attr
  350. * Sometimes lines in the GFF file are missing the required ID attribute that
  351. * specifies the unique name of the feature. If so, you may specify the
  352. * name of an existing attribute to use for the ID.
  353. * @param $create_organism
  354. * The Tripal GFF loader supports the "organism" attribute. This allows
  355. * features of a different organism to be aligned to the landmark sequence of
  356. * another species. The format of the attribute is "organism=[genus]:[species]",
  357. * where [genus] is the organism's genus and [species] is the species name.
  358. * Check this box to automatically add the organism to the database if it does
  359. * not already exists. Otherwise lines with an oraganism attribute where the
  360. * organism is not present in the database will be skipped.
  361. * @param $re_mrna A
  362. * regular expression to extract portions from mRNA id
  363. * @param $re_protein A
  364. * replacement string to generate the protein id
  365. *
  366. * @ingroup gff3_loader
  367. */
  368. private function loadGFF3($gff_file, $organism_id, $analysis_id,
  369. $add_only = 0, $update = 1, $refresh = 0, $remove = 0, $use_transaction = 1,
  370. $target_organism_id = NULL, $target_type = NULL, $create_target = 0,
  371. $start_line = 1, $landmark_type = '', $alt_id_attr = '', $create_organism = FALSE,
  372. $re_mrna = '', $re_protein = '') {
  373. $ret = array();
  374. $date = getdate();
  375. // An array that stores CVterms that have been looked up so we don't have
  376. // to do the database query every time.
  377. $cvterm_lookup = array();
  378. // An array that stores Landmarks that have been looked up so we don't have
  379. // to do the database query every time.
  380. $landmark_lookup = array();
  381. // empty the temp tables
  382. $sql = "DELETE FROM {tripal_gff_temp}";
  383. chado_query($sql);
  384. $sql = "DELETE FROM {tripal_gffcds_temp}";
  385. chado_query($sql);
  386. $sql = "DELETE FROM {tripal_gffprotein_temp}";
  387. chado_query($sql);
  388. // check to see if the file is located local to Drupal
  389. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $gff_file;
  390. if (!file_exists($dfile)) {
  391. // if not local to Drupal, the file must be someplace else, just use
  392. // the full path provided
  393. $dfile = $gff_file;
  394. }
  395. if (!file_exists($dfile)) {
  396. throw new Exception(t("Cannot find the file: !dfile", array('!dfile' => $dfile)));
  397. }
  398. $this->logMessage("Opening !gff_file", array('!gff_file' => $gff_file));
  399. //$lines = file($dfile,FILE_SKIP_EMPTY_LINES);
  400. $fh = fopen($dfile, 'r');
  401. if (!$fh) {
  402. throw new Exception(t("Cannot open file: !dfile", array('!dfile' => $dfile)));
  403. }
  404. $filesize = filesize($dfile);
  405. $this->setTotalItems($filesize);
  406. // get the controlled vocaubulary that we'll be using. The
  407. // default is the 'sequence' ontology
  408. $sql = "SELECT * FROM {cv} WHERE name = :cvname";
  409. $cv = chado_query($sql, array(':cvname' => 'sequence'))->fetchObject();
  410. if (!$cv) {
  411. throw new Exception(t("Cannot find the 'sequence' ontology", array()));
  412. }
  413. // get the organism for which this GFF3 file belongs
  414. $sql = "SELECT * FROM {organism} WHERE organism_id = :organism_id";
  415. $organism = chado_query($sql, array(':organism_id' => $organism_id))->fetchObject();
  416. $in_fasta = 0;
  417. $line_num = 0;
  418. $num_read = 0;
  419. // prepare the statement used to get the cvterm for each feature.
  420. $sel_cvterm_sql = "
  421. SELECT CVT.cvterm_id, CVT.cv_id, CVT.name, CVT.definition,
  422. CVT.dbxref_id, CVT.is_obsolete, CVT.is_relationshiptype
  423. FROM {cvterm} CVT
  424. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  425. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  426. WHERE CV.cv_id = :cv_id and
  427. (lower(CVT.name) = lower(:name) or lower(CVTS.synonym) = lower(:synonym))
  428. ";
  429. // If a landmark type was provided then pre-retrieve that.
  430. if ($landmark_type) {
  431. $query = array(
  432. ':cv_id' => $cv->cv_id,
  433. ':name' => $landmark_type,
  434. ':synonym' => $landmark_type
  435. );
  436. $result = chado_query($sel_cvterm_sql, $query);
  437. $landmark_cvterm = $result->fetchObject();
  438. if (!$landmark_cvterm) {
  439. throw new Exception(t('Cannot find landmark feature type \'%landmark_type\'.', array('%landmark_type' => $landmark_type)));
  440. }
  441. }
  442. // iterate through each line of the GFF file
  443. while ($line = fgets($fh)) {
  444. $line_num++;
  445. $size = drupal_strlen($line);
  446. $this->addItemsHandled($size);
  447. $num_read += $size;
  448. if ($line_num < $start_line) {
  449. continue;
  450. }
  451. // check to see if we have FASTA section, if so then set the variable
  452. // to start parsing
  453. if (preg_match('/^##FASTA/i', $line)) {
  454. $this->logMessage("Parsing FASTA portion...");
  455. if ($remove) {
  456. // we're done because this is a delete operation so break out of the loop.
  457. break;
  458. }
  459. $this->loadFasta($fh, $interval, $num_read, $line_num, $filesize);
  460. continue;
  461. }
  462. // if the ##sequence-region line is present then we want to add a new feature
  463. if (preg_match('/^##sequence-region (.*?) (\d+) (\d+)$/i', $line, $region_matches)) {
  464. $rid = $region_matches[1];
  465. $rstart = $region_matches[2];
  466. $rend = $region_matches[3];
  467. if ($landmark_type) {
  468. $this->loadFeature($organism, $analysis_id, $landmark_cvterm, $rid,
  469. $rid, '', 'f', 'f', 1, 0);
  470. }
  471. continue;
  472. }
  473. // skip comments
  474. if (preg_match('/^#/', $line)) {
  475. continue;
  476. }
  477. // skip empty lines
  478. if (preg_match('/^\s*$/', $line)) {
  479. continue;
  480. }
  481. // get the columns
  482. $cols = explode("\t", $line);
  483. if (sizeof($cols) != 9) {
  484. throw new Exception(t('Improper number of columns on line %line_num', array('%line_num' => $line_num)));
  485. }
  486. // get the column values
  487. $landmark = $cols[0];
  488. $source = $cols[1];
  489. $type = $cols[2];
  490. $start = $cols[3];
  491. $end = $cols[4];
  492. $score = $cols[5];
  493. $strand = $cols[6];
  494. $phase = $cols[7];
  495. $attrs = explode(";", $cols[8]); // split by a semicolon
  496. // ready the start and stop for chado. Chado expects these positions
  497. // to be zero-based, so we substract 1 from the fmin
  498. $fmin = $start - 1;
  499. $fmax = $end;
  500. if ($end < $start) {
  501. $fmin = $end - 1;
  502. $fmax = $start;
  503. }
  504. // format the strand for chado
  505. if (strcmp($strand, '.') == 0) {
  506. $strand = 0;
  507. }
  508. elseif (strcmp($strand, '+') == 0) {
  509. $strand = 1;
  510. }
  511. elseif (strcmp($strand, '-') == 0) {
  512. $strand = -1;
  513. }
  514. if (strcmp($phase, '.') == 0) {
  515. if ($type == 'CDS') {
  516. $phase = '0';
  517. }
  518. else {
  519. $phase = '';
  520. }
  521. }
  522. if (array_key_exists($type, $cvterm_lookup)) {
  523. $cvterm = $cvterm_lookup[$type];
  524. }
  525. else {
  526. $result = chado_query($sel_cvterm_sql, array(':cv_id' => $cv->cv_id, ':name' => $type, ':synonym' => $type));
  527. $cvterm = $result->fetchObject();
  528. $cvterm_lookup[$type] = $cvterm;
  529. if (!$cvterm) {
  530. throw new Exception(t('Cannot find feature term \'%type\' on line %line_num of the GFF file',
  531. array('%type' => $type, '%line_num' => $line_num)));
  532. }
  533. }
  534. // break apart each of the attributes
  535. $tags = array();
  536. $attr_name = '';
  537. $attr_uniquename = '';
  538. $attr_residue_info = '';
  539. $attr_locgroup = 0;
  540. $attr_fmin_partial = 'f';
  541. $attr_fmax_partial = 'f';
  542. $attr_is_obsolete = 'f';
  543. $attr_is_analysis = 'f';
  544. $attr_others = [];
  545. $residues = '';
  546. // the organism to which a feature belongs can be set in the GFF
  547. // file using the 'organism' attribute. By default we
  548. // set the $feature_organism variable to the default organism for the landmark
  549. $attr_organism = '';
  550. $feature_organism = $organism;
  551. foreach ($attrs as $attr) {
  552. $attr = rtrim($attr);
  553. $attr = ltrim($attr);
  554. if (strcmp($attr, '')==0) {
  555. continue;
  556. }
  557. if (!preg_match('/^[^\=]+\=.+$/', $attr)) {
  558. throw new Exception(t('Attribute is not correctly formatted on line %line_num: %attr',
  559. array('%line_num' => $line_num, '%attr' => $attr)));
  560. }
  561. // break apart each tag
  562. $tag = preg_split("/=/", $attr, 2); // split by equals sign
  563. // multiple instances of an attribute are separated by commas
  564. $tag_name = $tag[0];
  565. if (!array_key_exists($tag_name, $tags)) {
  566. $tags[$tag_name] = array();
  567. }
  568. $tags[$tag_name] = array_merge($tags[$tag_name], explode(",", $tag[1])); // split by comma
  569. // replace the URL escape codes for each tag
  570. for ($i = 0; $i < count($tags[$tag_name]); $i++) {
  571. $tags[$tag_name][$i] = urldecode($tags[$tag_name][$i]);
  572. }
  573. // get the name and ID tags
  574. $skip_feature = 0; // if there is a problem with any of the attributes this variable gets set
  575. if (strcmp($tag_name, 'ID') == 0) {
  576. $attr_uniquename = urldecode($tag[1]);
  577. }
  578. elseif (strcmp($tag_name, 'Name') == 0) {
  579. $attr_name = urldecode($tag[1]);
  580. }
  581. elseif (strcmp($tag_name, 'organism') == 0) {
  582. $attr_organism = urldecode($tag[1]);
  583. $org_matches = array();
  584. if (preg_match('/^(.*?):(.*?)$/', $attr_organism, $org_matches)) {
  585. $values = array(
  586. 'genus' => $org_matches[1],
  587. 'species' => $org_matches[2],
  588. );
  589. $org = chado_select_record('organism', array("*"), $values);
  590. if (count($org) == 0) {
  591. if ($create_organism) {
  592. $feature_organism = (object) chado_insert_record('organism', $values);
  593. if (!$feature_organism) {
  594. $this->logMessage("Could not add the organism, '%org', from line %line. Skipping this line.",
  595. array('%org' => $attr_organism, '%line' => $line_num), TRIPAL_ERROR);
  596. $skip_feature = 1;
  597. }
  598. }
  599. else {
  600. $this->logMessage("The organism attribute '%org' on line %line does not exist. Skipping this line.",
  601. array('%org' => $attr_organism, '%line' => $line_num), TRIPAL_ERROR);
  602. $skip_feature = 1;
  603. }
  604. }
  605. else {
  606. // We found the organism in the database so use it.
  607. $feature_organism = $org[0];
  608. }
  609. }
  610. else {
  611. $this->logMessage("The organism attribute '%org' on line %line is not properly formated. It " .
  612. "should be of the form: organism=Genus:species. Skipping this line.",
  613. array('%org' => $attr_organism, '%line' => $line_num), TRIPAL_ERROR);
  614. $skip_feature = 1;
  615. }
  616. }
  617. // Get the list of non-reserved attributes.
  618. elseif (strcmp($tag_name, 'Alias') != 0 and strcmp($tag_name, 'Parent') != 0 and
  619. strcmp($tag_name, 'Target') != 0 and strcmp($tag_name, 'Gap') != 0 and
  620. strcmp($tag_name, 'Derives_from') != 0 and strcmp($tag_name, 'Note') != 0 and
  621. strcmp($tag_name, 'Dbxref') != 0 and strcmp($tag_name, 'Ontology_term') != 0 and
  622. strcmp($tag_name, 'Is_circular') != 0 and strcmp($tag_name, 'target_organism') != 0 and
  623. strcmp($tag_name, 'target_type') != 0 and strcmp($tag_name, 'organism' != 0)) {
  624. foreach ($tags[$tag_name] as $value) {
  625. $attr_others[$tag_name][] = $value;
  626. }
  627. }
  628. }
  629. // If neither name nor uniquename are provided then generate one.
  630. if (!$attr_uniquename and !$attr_name) {
  631. // Check if an alternate ID field is suggested, if so, then use
  632. // that for the name.
  633. if (array_key_exists($alt_id_attr, $tags)) {
  634. $attr_uniquename = $tags[$alt_id_attr][0];
  635. $attr_name = $attr_uniquename;
  636. }
  637. // If the row has a parent then generate a uniquename using the parent name
  638. // add the date to the name in the event there are more than one child with
  639. // the same parent.
  640. elseif (array_key_exists('Parent', $tags)) {
  641. $attr_uniquename = $tags['Parent'][0] . "-$type-$landmark-" . $date[0] . ":" . ($fmin + 1) . ".." . $fmax;
  642. $attr_name = $attr_uniquename;
  643. }
  644. // Generate a unique name based on the date, type and location
  645. // and set the name to simply be the type.
  646. else {
  647. $attr_uniquename = $date[0] . "-$type-$landmark:" . ($fmin + 1) . ".." . $fmax;
  648. $attr_name = $type;
  649. }
  650. }
  651. // If a name is not specified then use the unique name as the name
  652. if (strcmp($attr_name, '') == 0) {
  653. $attr_name = $attr_uniquename;
  654. }
  655. // If an ID attribute is not specified then we must generate a
  656. // unique ID. Do this by combining the attribute name with the date
  657. // and line number.
  658. if (!$attr_uniquename) {
  659. $attr_uniquename = $attr_name . '-' . $date[0] . '-' . $line_num;
  660. }
  661. // Make sure the landmark sequence exists in the database. If the user
  662. // has not specified a landmark type (and it's not required in the GFF
  663. // format) then we don't know the type of the landmark so we'll hope
  664. // that it's unique across all types for the organism. Only do this
  665. // test if the landmark and the feature are different.
  666. if (!$remove and !(strcmp($landmark, $attr_uniquename) == 0 or strcmp($landmark, $attr_name) == 0) and !in_array($landmark, $landmark_lookup)) {
  667. $select = array(
  668. 'organism_id' => $organism->organism_id,
  669. 'uniquename' => $landmark,
  670. );
  671. $columns = array('count(*) as num_landmarks');
  672. if ($landmark_type) {
  673. $select['type_id'] = array(
  674. 'name' => $landmark_type,
  675. );
  676. }
  677. $count = chado_select_record('feature', $columns, $select);
  678. if (!$count or count($count) == 0 or $count[0]->num_landmarks == 0) {
  679. // now look for the landmark using the name rather than uniquename.
  680. $select = array(
  681. 'organism_id' => $organism->organism_id,
  682. 'name' => $landmark,
  683. );
  684. $columns = array('count(*) as num_landmarks');
  685. if ($landmark_type) {
  686. $select['type_id'] = array(
  687. 'name' => $landmark_type,
  688. );
  689. }
  690. $count = chado_select_record('feature', $columns, $select);
  691. if (!$count or count($count) == 0 or $count[0]->num_landmarks == 0) {
  692. throw new Exception(t("The landmark '%landmark' cannot be found for this organism (%species) " .
  693. "Please add the landmark and then retry the import of this GFF3 " .
  694. "file", array('%landmark' => $landmark, '%species' => $organism->genus . " " . $organism->species)));
  695. }
  696. elseif ($count[0]->num_landmarks > 1) {
  697. throw new Exception(t("The landmark '%landmark' has more than one entry for this organism (%species) " .
  698. "Cannot continue", array('%landmark' => $landmark, '%species' => $organism->genus . " " . $organism->species)));
  699. }
  700. }
  701. if ($count[0]->num_landmarks > 1) {
  702. throw new Exception(t("The landmark '%landmark' is not unique for this organism. " .
  703. "The features cannot be associated", array('%landmark' => $landmark)));
  704. }
  705. // The landmark was found, remember it
  706. $landmark_lookup[] = $landmark;
  707. }
  708. /*
  709. // If the option is to remove or refresh then we want to remove
  710. // the feature from the database.
  711. if ($remove or $refresh) {
  712. // Next remove the feature itself.
  713. $sql = "DELETE FROM {feature}
  714. WHERE organism_id = %d and uniquename = '%s' and type_id = %d";
  715. $match = array(
  716. 'organism_id' => $feature_organism->organism_id,
  717. 'uniquename' => $attr_uniquename,
  718. 'type_id' => $cvterm->cvterm_id
  719. );
  720. $result = chado_delete_record('feature', $match);
  721. if (!$result) {
  722. $this->logMessage("Cannot delete feature %attr_uniquename",
  723. array('%attr_uniquename' => $attr_uniquename), TRIPAL_ERROR);
  724. }
  725. $feature = 0;
  726. unset($result);
  727. }
  728. */
  729. // Add or update the feature and all properties.
  730. if ($update or $refresh or $add_only) {
  731. // Add/update the feature.
  732. $feature = $this->loadFeature($feature_organism, $analysis_id, $cvterm,
  733. $attr_uniquename, $attr_name, $residues, $attr_is_analysis,
  734. $attr_is_obsolete, $add_only, $score);
  735. if ($feature) {
  736. // Add a record for this feature to the tripal_gff_temp table for
  737. // later lookup.
  738. $values = array(
  739. 'feature_id' => $feature->feature_id,
  740. 'organism_id' => $feature->organism_id,
  741. 'type_name' => $type,
  742. 'uniquename' => $feature->uniquename
  743. );
  744. // make sure this record doesn't already exist in our temp table
  745. $results = chado_select_record('tripal_gff_temp', array('*'), $values);
  746. if (count($results) == 0) {
  747. $result = chado_insert_record('tripal_gff_temp', $values);
  748. if (!$result) {
  749. throw new Exception(t("Cound not save record in temporary table, Cannot continue.", array()));
  750. }
  751. }
  752. // add/update the featureloc if the landmark and the ID are not the same
  753. // if they are the same then this entry in the GFF is probably a landmark identifier
  754. if (strcmp($landmark, $attr_uniquename) !=0 ) {
  755. $this->loadFeatureLoc($feature, $organism,
  756. $landmark, $fmin, $fmax, $strand, $phase, $attr_fmin_partial,
  757. $attr_fmax_partial, $attr_residue_info, $attr_locgroup);
  758. }
  759. // add any aliases for this feature
  760. if (array_key_exists('Alias', $tags)) {
  761. $this->loadAlias($feature, $tags['Alias']);
  762. }
  763. // add any dbxrefs for this feature
  764. if (array_key_exists('Dbxref', $tags)) {
  765. $this->loadDbxref($feature, $tags['Dbxref']);
  766. }
  767. // add any ontology terms for this feature
  768. if (array_key_exists('Ontology_term', $tags)) {
  769. $this->loadOntology($feature, $tags['Ontology_term']);
  770. }
  771. // add parent relationships
  772. if (array_key_exists('Parent', $tags)) {
  773. $this->loadParents($feature, $cvterm, $tags['Parent'],
  774. $feature_organism->organism_id, $strand, $phase, $fmin, $fmax);
  775. }
  776. // add target relationships
  777. if (array_key_exists('Target', $tags)) {
  778. $this->loadTarget($feature, $tags, $target_organism_id, $target_type, $create_target, $attr_locgroup);
  779. }
  780. // add gap information. This goes in simply as a property
  781. if (array_key_exists('Gap', $tags)) {
  782. foreach ($tags['Gap'] as $value) {
  783. $this->loadProperty($feature, 'Gap', $value);
  784. }
  785. }
  786. // add notes. This goes in simply as a property
  787. if (array_key_exists('Note', $tags)) {
  788. foreach ($tags['Note'] as $value) {
  789. $this->loadProperty($feature, 'Note', $value);
  790. }
  791. }
  792. // add the Derives_from relationship (e.g. polycistronic genes).
  793. if (array_key_exists('Derives_from', $tags)) {
  794. $this->loadDerivesFrom($feature, $cvterm, $tags['Derives_from'][0],
  795. $feature_organism, $fmin, $fmax);
  796. }
  797. // add in the GFF3_source dbxref so that GBrowse can find the feature using the source column
  798. $source_ref = array('GFF_source:' . $source);
  799. $this->loadDbxref($feature, $source_ref);
  800. // add any additional attributes
  801. if ($attr_others) {
  802. foreach ($attr_others as $tag_name => $values) {
  803. foreach ($values as $value) {
  804. $this->loadProperty($feature, $tag_name, $value);
  805. }
  806. }
  807. }
  808. }
  809. }
  810. }
  811. // Do some last bit of processing.
  812. if (!$remove) {
  813. // First, add any protein sequences if needed.
  814. $sql = "SELECT feature_id FROM {tripal_gffcds_temp} LIMIT 1 OFFSET 1";
  815. $has_cds = chado_query($sql)->fetchField();
  816. if ($has_cds) {
  817. $this->logMessage("\nAdding protein sequences if CDS exist and no proteins in GFF...");
  818. $sql = "
  819. SELECT F.feature_id, F.name, F.uniquename, TGCT.strand,
  820. CVT.cvterm_id, CVT.name as feature_type,
  821. min(TGCT.fmin) as fmin, max(TGCT.fmax) as fmax,
  822. TGPT.feature_id as protein_id, TGPT.fmin as protein_fmin,
  823. TGPT.fmax as protein_fmax, FLM.uniquename as landmark
  824. FROM {tripal_gffcds_temp} TGCT
  825. INNER JOIN {feature} F on F.feature_id = TGCT.parent_id
  826. INNER JOIN {cvterm} CVT on CVT.cvterm_id = F.type_id
  827. INNER JOIN {featureloc} L on F.feature_id = L.feature_id
  828. INNER JOIN {feature} FLM on L.srcfeature_id = FLM.feature_id
  829. LEFT JOIN {tripal_gffprotein_temp} TGPT on TGPT.parent_id = F.feature_id
  830. GROUP BY F.feature_id, F.name, F.uniquename, CVT.cvterm_id, CVT.name,
  831. TGPT.feature_id, TGPT.fmin, TGPT.fmax, TGCT.strand, FLM.uniquename
  832. ";
  833. $results = chado_query($sql);
  834. $protein_cvterm = chado_get_cvterm(array(
  835. 'name' => 'polypeptide',
  836. 'cv_id' => array(
  837. 'name' => 'sequence'
  838. )
  839. ));
  840. while ($result = $results->fetchObject()) {
  841. // If a protein exists with this same parent then don't add a new
  842. // protein.
  843. if (!$result->protein_id) {
  844. // Get details about this protein
  845. if ($re_mrna and $re_protein) {
  846. // We use a regex to generate protein name from mRNA name
  847. $uname = preg_replace("/$re_mrna/", $re_protein, $result->uniquename);
  848. $name = $result->name;
  849. }
  850. else {
  851. // No regex, use the default '-protein' suffix
  852. $uname = $result->uniquename . '-protein';
  853. $name = $result->name;
  854. }
  855. $values = array(
  856. 'parent_id' => $result->feature_id,
  857. 'fmin' => $result->fmin
  858. );
  859. $min_phase = chado_select_record('tripal_gffcds_temp', array('phase'), $values);
  860. $values = array(
  861. 'parent_id' => $result->feature_id,
  862. 'fmax' => $result->fmax
  863. );
  864. $max_phase = chado_select_record('tripal_gffcds_temp', array('phase'), $values);
  865. $pfmin = $result->fmin;
  866. $pfmax = $result->fmax;
  867. if ($result->strand == '-1') {
  868. $pfmax -= $max_phase[0]->phase;
  869. }
  870. else {
  871. $pfmin += $min_phase[0]->phase;
  872. }
  873. // Add the new protein record.
  874. $feature = $this->loadFeature($organism, $analysis_id,
  875. $protein_cvterm, $uname, $name, '', 'f', 'f', 1, 0);
  876. // Add the derives_from relationship.
  877. $cvterm = chado_get_cvterm(array('cvterm_id' => $result->cvterm_id));
  878. $this->loadDerivesFrom($feature, $cvterm,
  879. $result->uniquename, $organism, $pfmin, $pfmax);
  880. // Add the featureloc record. Set the start of the protein to
  881. // be the start of the coding sequence minus the phase.
  882. $this->loadFeatureLoc($feature, $organism, $result->landmark,
  883. $pfmin, $pfmax, $result->strand, '', 'f', 'f', '', 0);
  884. }
  885. }
  886. }
  887. $this->logMessage("Setting ranks of children...");
  888. // Get features in a relationship that are also children of an alignment.
  889. $sql = "
  890. SELECT DISTINCT F.feature_id, F.organism_id, F.type_id,
  891. F.uniquename, FL.strand
  892. FROM {tripal_gff_temp} TGT
  893. INNER JOIN {feature} F ON TGT.feature_id = F.feature_id
  894. INNER JOIN {feature_relationship} FR ON FR.object_id = TGT.feature_id
  895. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = FR.type_id
  896. INNER JOIN {featureloc} FL ON FL.feature_id = F.feature_id
  897. WHERE CVT.name = 'part_of'
  898. ";
  899. $parents = chado_query($sql);
  900. // Build and prepare the SQL for selecting the children relationship.
  901. $sel_gffchildren_sql = "
  902. SELECT DISTINCT FR.feature_relationship_id, FL.fmin, FR.rank
  903. FROM {feature_relationship} FR
  904. INNER JOIN {featureloc} FL on FL.feature_id = FR.subject_id
  905. INNER JOIN {cvterm} CVT on CVT.cvterm_id = FR.type_id
  906. WHERE FR.object_id = :feature_id AND CVT.name = 'part_of'
  907. ORDER BY FL.fmin ASC
  908. ";
  909. // Now set the rank of any parent/child relationships. The order is based
  910. // on the fmin. The start rank is 1. This allows features with other
  911. // relationships to be '0' (the default), and doesn't interfer with the
  912. // ordering defined here.
  913. $num_recs = $parents->rowCount();
  914. $i = 1;
  915. while ($parent = $parents->fetchObject()) {
  916. // get the children
  917. $result = chado_query($sel_gffchildren_sql, array(':feature_id' => $parent->feature_id));
  918. // build an array of the children
  919. $children = array();
  920. while ($child = $result->fetchObject()) {
  921. $children[] = $child;
  922. }
  923. // the children list comes sorted in ascending fmin
  924. // but if the parent is on the reverse strand we need to
  925. // reverse the order of the children.
  926. if ($parent->strand == -1) {
  927. arsort($children);
  928. }
  929. // first set the ranks to a negative number so that we don't
  930. // get a duplicate error message when we try to change any of them
  931. $rank = -1;
  932. foreach ($children as $child) {
  933. $match = array('feature_relationship_id' => $child->feature_relationship_id);
  934. $values = array('rank' => $rank);
  935. chado_update_record('feature_relationship', $match, $values);
  936. $rank--;
  937. }
  938. // now set the rank correctly. The rank should start at 0.
  939. $rank = 0;
  940. foreach ($children as $child) {
  941. $match = array('feature_relationship_id' => $child->feature_relationship_id);
  942. $values = array('rank' => $rank);
  943. chado_update_record('feature_relationship', $match, $values);
  944. $rank++;
  945. }
  946. $i++;
  947. }
  948. }
  949. return 1;
  950. }
  951. /**
  952. * Load the derives from attribute for a gff3 feature
  953. *
  954. * @param $feature
  955. * @param $subject
  956. * @param $organism
  957. *
  958. * @ingroup gff3_loader
  959. */
  960. private function loadDerivesFrom($feature, $cvterm, $object,
  961. $organism, $fmin, $fmax) {
  962. $type = $cvterm->name;
  963. // First look for the object feature in the temp table to get it's type.
  964. $values = array(
  965. 'organism_id' => $organism->organism_id,
  966. 'uniquename' => $object,
  967. );
  968. $result = chado_select_record('tripal_gff_temp', array('type_name'), $values);
  969. $type_id = NULL;
  970. if (count($result) > 0) {
  971. $otype = chado_get_cvterm(array(
  972. 'name' => $result[0]->type_name,
  973. 'cv_id' => array(
  974. 'name' => 'sequence'
  975. )
  976. ));
  977. if ($otype) {
  978. $type_id = $otype->cvterm_id;
  979. }
  980. }
  981. // If the object wasn't in the temp table then look for it in the
  982. // feature table and get it's type.
  983. if (!$type_id) {
  984. $result = chado_select_record('feature', array('type_id'), $values);
  985. if (count($result) > 1) {
  986. $this->logMessage("Cannot find feature type for, '!subject' , in 'derives_from' relationship. Multiple matching features exist with this uniquename.",
  987. array('!subject' => $object), TRIPAL_WARNING);
  988. return;
  989. }
  990. else if (count($result) == 0) {
  991. $this->logMessage("Cannot find feature type for, '!subject' , in 'derives_from' relationship.",
  992. array('!subject' => $object), TRIPAL_WARNING);
  993. return '';
  994. }
  995. else {
  996. $type_id = $result->type_id;
  997. }
  998. }
  999. // Get the object feature.
  1000. $match = array(
  1001. 'organism_id' => $organism->organism_id,
  1002. 'uniquename' => $object,
  1003. 'type_id' => $type_id,
  1004. );
  1005. $ofeature = chado_select_record('feature', array('feature_id'), $match);
  1006. if (count($ofeature) == 0) {
  1007. $this->logMessage("Could not add 'Derives_from' relationship " .
  1008. "for %uniquename and %subject. Subject feature, '%subject', " .
  1009. "cannot be found.", array('%uniquename' => $feature->uniquename, '%subject' => $subject), TRIPAL_ERROR);
  1010. return;
  1011. }
  1012. // If this feature is a protein then add it to the tripal_gffprotein_temp.
  1013. if ($type == 'protein' or $type == 'polypeptide') {
  1014. $values = array(
  1015. 'feature_id' => $feature->feature_id,
  1016. 'parent_id' => $ofeature[0]->feature_id,
  1017. 'fmin' => $fmin,
  1018. 'fmax' => $fmax
  1019. );
  1020. $result = chado_insert_record('tripal_gffprotein_temp', $values);
  1021. if (!$result) {
  1022. throw new Exception(t("Cound not save record in temporary protein table, Cannot continue.", array()));
  1023. }
  1024. }
  1025. // Now check to see if the relationship already exists. If it does
  1026. // then just return.
  1027. $values = array(
  1028. 'object_id' => $ofeature[0]->feature_id,
  1029. 'subject_id' => $feature->feature_id,
  1030. 'type_id' => array(
  1031. 'cv_id' => array(
  1032. 'name' => 'sequence'
  1033. ),
  1034. 'name' => 'derives_from',
  1035. ),
  1036. 'rank' => 0
  1037. );
  1038. $rel = chado_select_record('feature_relationship', array('*'), $values);
  1039. if (count($rel) > 0) {
  1040. return;
  1041. }
  1042. // finally insert the relationship if it doesn't exist
  1043. $ret = chado_insert_record('feature_relationship', $values);
  1044. if (!$ret) {
  1045. $this->logMessage("Could not add 'Derives_from' relationship for :uniquename and :subject.",
  1046. array(':uniquename' => $feature->uniquename, ':subject' => $subject), TRIPAL_WARNING);
  1047. }
  1048. }
  1049. /**
  1050. * Load the parents for a gff3 feature
  1051. *
  1052. * @param $feature
  1053. * @param $cvterm
  1054. * @param $parents
  1055. * @param $organism_id
  1056. * @param $fmin
  1057. *
  1058. * @ingroup gff3_loader
  1059. */
  1060. private function loadParents($feature, $cvterm, $parents,
  1061. $organism_id, $strand, $phase, $fmin, $fmax) {
  1062. $uname = $feature->uniquename;
  1063. $type = $cvterm->name;
  1064. $rel_type = 'part_of';
  1065. // Prepare these SQL statements that will be used repeatedly.
  1066. $cvterm_sql = "
  1067. SELECT CVT.cvterm_id
  1068. FROM {cvterm} CVT
  1069. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  1070. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  1071. WHERE cv.name = :cvname and (CVT.name = :name or CVTS.synonym = :synonym)
  1072. ";
  1073. // Iterate through the parents in the list.
  1074. foreach ($parents as $parent) {
  1075. // Get the parent cvterm.
  1076. $values = array(
  1077. 'organism_id' => $organism_id,
  1078. 'uniquename' => $parent,
  1079. );
  1080. $result = chado_select_record('tripal_gff_temp', array('type_name'), $values);
  1081. if (count($result) == 0) {
  1082. $this->logMessage("Cannot find parent: %parent.", array('%parent' => $parent), TRIPAL_WARNING);
  1083. return '';
  1084. }
  1085. $parent_type = $result[0]->type_name;
  1086. // try to find the parent
  1087. $parentcvterm = chado_query($cvterm_sql, array(':cvname' => 'sequence', ':name' => $parent_type, ':synonym' => $parent_type))->fetchObject();
  1088. $relcvterm = chado_query($cvterm_sql, array(':cvname' => 'sequence', ':name' => $rel_type, ':synonym' => $rel_type))->fetchObject();
  1089. if (!$relcvterm) {
  1090. throw new Exception(t("Cannot find the term, 'part_of', from the sequence ontology. This term is used for associating parent and children features. Please check that the ontology is fully imported."));
  1091. }
  1092. $values = array(
  1093. 'organism_id' => $organism_id,
  1094. 'uniquename' => $parent,
  1095. 'type_id' => $parentcvterm->cvterm_id,
  1096. );
  1097. $result = chado_select_record('feature', array('feature_id'), $values);
  1098. $parent_feature = $result[0];
  1099. // if the parent exists then add the relationship otherwise print error and skip
  1100. if ($parent_feature) {
  1101. // check to see if the relationship already exists
  1102. $values = array(
  1103. 'object_id' => $parent_feature->feature_id,
  1104. 'subject_id' => $feature->feature_id,
  1105. 'type_id' => $relcvterm->cvterm_id,
  1106. );
  1107. $rel = chado_select_record('feature_relationship', array('*'), $values);
  1108. if (count($rel) > 0) {
  1109. }
  1110. else {
  1111. // the relationship doesn't already exist, so add it.
  1112. $values = array(
  1113. 'subject_id' => $feature->feature_id,
  1114. 'object_id' => $parent_feature->feature_id,
  1115. 'type_id' => $relcvterm->cvterm_id,
  1116. );
  1117. $result = chado_insert_record('feature_relationship', $values);
  1118. if (!$result) {
  1119. $this->logMessage("Failed to insert feature relationship '$uname' ($type) $rel_type '$parent' ($parent_type).",
  1120. array(), TRIPAL_WARNING);
  1121. }
  1122. }
  1123. // If this feature is a CDS and now that we know the parent we can
  1124. // add it to the tripal_gffcds_temp table for later lookup.
  1125. if ($type == 'CDS') {
  1126. $values = array(
  1127. 'feature_id' => $feature->feature_id,
  1128. 'parent_id' => $parent_feature->feature_id,
  1129. 'fmin' => $fmin,
  1130. 'fmax' => $fmax,
  1131. 'strand' => $strand,
  1132. );
  1133. if (isset($phase)) {
  1134. $values['phase'] = $phase;
  1135. }
  1136. $result = chado_insert_record('tripal_gffcds_temp', $values);
  1137. if (!$result) {
  1138. throw new Exception(t("Cound not save record in temporary CDS table, Cannot continue.", array()));
  1139. exit;
  1140. }
  1141. }
  1142. }
  1143. else {
  1144. $this->logMessage("Cannot establish relationship '$uname' ($type) $rel_type '$parent' ($parent_type): Cannot find the parent.",
  1145. array(), TRIPAL_WARNING);
  1146. }
  1147. }
  1148. }
  1149. /**
  1150. * Load the dbxref attribute for a feature
  1151. *
  1152. * @param $feature
  1153. * @param $dbxrefs
  1154. *
  1155. * @ingroup gff3_loader
  1156. */
  1157. private function loadDbxref($feature, $dbxrefs) {
  1158. // iterate through each of the dbxrefs
  1159. foreach ($dbxrefs as $dbxref) {
  1160. // get the database name from the reference. If it doesn't exist then create one.
  1161. $ref = explode(":", $dbxref);
  1162. $dbname = trim($ref[0]);
  1163. $accession = trim($ref[1]);
  1164. // first look for the database name if it doesn't exist then create one.
  1165. // first check for the fully qualified URI (e.g. DB:<dbname>. If that
  1166. // can't be found then look for the name as is. If it still can't be found
  1167. // the create the database
  1168. $values = array('name' => "DB:$dbname");
  1169. $db = chado_select_record('db', array('db_id'), $values);
  1170. if (count($db) == 0) {
  1171. $values = array('name' => "$dbname");
  1172. $db = chado_select_record('db', array('db_id'), $values);
  1173. }
  1174. if (count($db) == 0) {
  1175. $values = array(
  1176. 'name' => $dbname,
  1177. 'description' => 'Added automatically by the GFF loader'
  1178. );
  1179. $success = chado_insert_record('db', $values);
  1180. if ($success) {
  1181. $values = array('name' => "$dbname");
  1182. $db = chado_select_record('db', array('db_id'), $values);
  1183. }
  1184. else {
  1185. $this->logMessage("Cannot find or add the database $dbname.", array(), TRIPAL_WARNING);
  1186. return 0;
  1187. }
  1188. }
  1189. $db = $db[0];
  1190. // now check to see if the accession exists
  1191. $values = array(
  1192. 'accession' => $accession,
  1193. 'db_id' => $db->db_id
  1194. );
  1195. $dbxref = chado_select_record('dbxref', array('dbxref_id'), $values);
  1196. // if the accession doesn't exist then we want to add it
  1197. if (sizeof($dbxref) == 0) {
  1198. $values = array(
  1199. 'db_id' => $db->db_id,
  1200. 'accession' => $accession,
  1201. 'version' => ''
  1202. );
  1203. $ret = chado_insert_record('dbxref', $values);
  1204. $values = array(
  1205. 'accession' => $accession,
  1206. 'db_id' => $db->db_id
  1207. );
  1208. $dbxref = chado_select_record('dbxref', array('dbxref_id'), $values);
  1209. }
  1210. $dbxref = $dbxref[0];
  1211. // check to see if this feature dbxref already exists
  1212. $values = array(
  1213. 'dbxref_id' => $dbxref->dbxref_id,
  1214. 'feature_id' => $feature->feature_id
  1215. );
  1216. $fdbx = chado_select_record('feature_dbxref', array('feature_dbxref_id'), $values);
  1217. // now associate this feature with the database reference if it doesn't
  1218. // already exist
  1219. if (sizeof($fdbx) == 0) {
  1220. $values = array(
  1221. 'dbxref_id' => $dbxref->dbxref_id,
  1222. 'feature_id' => $feature->feature_id
  1223. );
  1224. $success = chado_insert_record('feature_dbxref', $values);
  1225. if (!$success) {
  1226. $this->logMessage("Failed to insert Dbxref: $dbname:$accession.", array(), TRIPAL_WARNING);
  1227. return 0;
  1228. }
  1229. }
  1230. }
  1231. return 1;
  1232. }
  1233. /**
  1234. * Load the cvterms for a feature.
  1235. *
  1236. * Assumes there is a dbxref.accession matching a cvterm.name
  1237. *
  1238. * @param $feature
  1239. * @param $dbxrefs
  1240. *
  1241. * @ingroup gff3_loader
  1242. */
  1243. private function loadOntology($feature, $dbxrefs) {
  1244. // iterate through each of the dbxrefs
  1245. foreach ($dbxrefs as $dbxref) {
  1246. // get the database name from the reference. If it doesn't exist then create one.
  1247. $ref = explode(":", $dbxref);
  1248. $dbname = trim($ref[0]);
  1249. $accession = trim($ref[1]);
  1250. // first look for the database name
  1251. $db = chado_select_record('db', array('db_id'), array('name' => "DB:$dbname"));
  1252. if (sizeof($db) == 0) {
  1253. // now look for the name without the 'DB:' prefix.
  1254. $db = chado_select_record('db', array('db_id'), array('name' => "$dbname"));
  1255. if (sizeof($db) == 0) {
  1256. $this->logMessage("Database, $dbname, is not present. Cannot associate term: $dbname:$accession.", array(), TRIPAL_WARNING);
  1257. return 0;
  1258. }
  1259. }
  1260. $db = $db[0];
  1261. // now check to see if the accession exists
  1262. $dbxref = chado_select_record('dbxref', array('dbxref_id'),
  1263. array('accession' => $accession, 'db_id' => $db->db_id));
  1264. if (sizeof($dbxref) == 0) {
  1265. $this->logMessage("Accession, $accession is missing for reference: $dbname:$accession.", array(), TRIPAL_WARNING);
  1266. return 0;
  1267. }
  1268. $dbxref = $dbxref[0];
  1269. // now check to see if the cvterm exists
  1270. $cvterm = chado_select_record('cvterm', array('cvterm_id'), array(
  1271. 'dbxref_id' => $dbxref->dbxref_id));
  1272. // if it doesn't exist in the cvterm table, look for an alternate id
  1273. if (sizeof($cvterm) == 0) {
  1274. $cvterm = chado_select_record('cvterm_dbxref', array('cvterm_id'), array(
  1275. 'dbxref_id' => $dbxref->dbxref_id));
  1276. if (sizeof($cvterm) == 0) {
  1277. $this->logMessage("CV Term is missing for reference: $dbname:$accession.", array(), TRIPAL_WARNING);
  1278. return 0;
  1279. }
  1280. }
  1281. $cvterm = $cvterm[0];
  1282. // check to see if this feature cvterm already exists
  1283. $fcvt = chado_select_record('feature_cvterm', array('feature_cvterm_id'),
  1284. array('cvterm_id' => $cvterm->cvterm_id, 'feature_id' => $feature->feature_id));
  1285. // now associate this feature with the cvterm if it doesn't already exist
  1286. if (sizeof($fcvt)==0) {
  1287. $values = array(
  1288. 'cvterm_id' => $cvterm->cvterm_id,
  1289. 'feature_id' => $feature->feature_id,
  1290. 'pub_id' => array(
  1291. 'uniquename' => 'null',
  1292. ),
  1293. );
  1294. $success = chado_insert_record('feature_cvterm', $values);
  1295. if (!$success) {
  1296. $this->logMessage("Failed to insert ontology term: $dbname:$accession.", array(), TRIPAL_WARNING);
  1297. return 0;
  1298. }
  1299. }
  1300. }
  1301. return 1;
  1302. }
  1303. /**
  1304. * Load any aliases for a feature
  1305. *
  1306. * @param $feature
  1307. * @param $aliases
  1308. *
  1309. * @ingroup gff3_loader
  1310. */
  1311. private function loadAlias($feature, $aliases) {
  1312. // make sure we have a 'synonym_type' vocabulary
  1313. $select = array('name' => 'synonym_type');
  1314. $results = chado_select_record('cv', array('*'), $select);
  1315. if (count($results) == 0) {
  1316. // insert the 'synonym_type' vocabulary
  1317. $values = array(
  1318. 'name' => 'synonym_type',
  1319. 'definition' => 'vocabulary for synonym types',
  1320. );
  1321. $success = chado_insert_record('cv', $values);
  1322. if (!$success) {
  1323. $this->logMessage("Failed to add the synonyms type vocabulary.", array(), TRIPAL_WARNING);
  1324. return 0;
  1325. }
  1326. // now that we've added the cv we need to get the record
  1327. $results = chado_select_record('cv', array('*'), $select);
  1328. if (count($results) > 0) {
  1329. $syncv = $results[0];
  1330. }
  1331. }
  1332. else {
  1333. $syncv = $results[0];
  1334. }
  1335. // get the 'exact' cvterm, which is the type of synonym we're adding
  1336. $select = array(
  1337. 'name' => 'exact',
  1338. 'cv_id' => array(
  1339. 'name' => 'synonym_type'
  1340. ),
  1341. );
  1342. $result = chado_select_record('cvterm', array('*'), $select);
  1343. if (count($result) == 0) {
  1344. $term = array(
  1345. 'name' => 'exact',
  1346. 'id' => "synonym_type:exact",
  1347. 'definition' => '',
  1348. 'is_obsolete' => 0,
  1349. 'cv_name' => $syncv->name,
  1350. 'is_relationship' => FALSE
  1351. );
  1352. $syntype = chado_insert_cvterm($term, array('update_existing' => TRUE));
  1353. if (!$syntype) {
  1354. $this->logMessage("Cannot add synonym type: internal:$type.", array(), TRIPAL_WARNING);
  1355. return 0;
  1356. }
  1357. }
  1358. else {
  1359. $syntype = $result[0];
  1360. }
  1361. // iterate through all of the aliases and add each one
  1362. foreach ($aliases as $alias) {
  1363. // check to see if the alias already exists in the synonym table
  1364. // if not, then add it
  1365. $select = array(
  1366. 'name' => $alias,
  1367. 'type_id' => $syntype->cvterm_id,
  1368. );
  1369. $result = chado_select_record('synonym', array('*'), $select);
  1370. if (count($result) == 0) {
  1371. $values = array(
  1372. 'name' => $alias,
  1373. 'type_id' => $syntype->cvterm_id,
  1374. 'synonym_sgml' => '',
  1375. );
  1376. $success = chado_insert_record('synonym', $values);
  1377. if (!$success) {
  1378. $this->logMessage("Cannot add alias $alias to synonym table.", array(), TRIPAL_WARNING);
  1379. return 0;
  1380. }
  1381. $result = chado_select_record('synonym', array('*'), $select);
  1382. $synonym = $result[0];
  1383. }
  1384. else {
  1385. $synonym = $result[0];
  1386. }
  1387. // check to see if we have a NULL publication in the pub table. If not,
  1388. // then add one.
  1389. $select = array('uniquename' => 'null');
  1390. $result = chado_select_record('pub', array('*'), $select);
  1391. if (count($result) == 0) {
  1392. $pub_sql = "
  1393. INSERT INTO {pub} (uniquename,type_id)
  1394. VALUES (:uname,
  1395. (SELECT cvterm_id
  1396. FROM {cvterm} CVT
  1397. INNER JOIN {dbxref} DBX ON DBX.dbxref_id = CVT.dbxref_id
  1398. INNER JOIN {db} DB ON DB.db_id = DBX.db_id
  1399. WHERE CVT.name = :type_id))
  1400. ";
  1401. $status = chado_query($psql);
  1402. if (!$status) {
  1403. $this->logMessage("Cannot prepare statement 'ins_pub_uniquename_typeid.", array(), TRIPAL_WARNING);
  1404. return 0;
  1405. }
  1406. // insert the null pub
  1407. $result = chado_query($pub_sql, array(':uname' => 'null', ':type_id' => 'null'))->fetchObject();
  1408. if (!$result) {
  1409. $this->logMessage("Cannot add null publication needed for setup of alias.", array(), TRIPAL_WARNING);
  1410. return 0;
  1411. }
  1412. $result = chado_select_record('pub', array('*'), $select);
  1413. $pub = $result[0];
  1414. }
  1415. else {
  1416. $pub = $result[0];
  1417. }
  1418. // check to see if the synonym exists in the feature_synonym table
  1419. // if not, then add it.
  1420. $values = array(
  1421. 'synonym_id' => $synonym->synonym_id,
  1422. 'feature_id' => $feature->feature_id,
  1423. 'pub_id' => $pub->pub_id,
  1424. );
  1425. $columns = array('feature_synonym_id');
  1426. $result = chado_select_record('feature_synonym', $columns, $values);
  1427. if (count($result) == 0) {
  1428. $values = array(
  1429. 'synonym_id' => $synonym->synonym_id,
  1430. 'feature_id' => $feature->feature_id,
  1431. 'pub_id' => $pub->pub_id,
  1432. );
  1433. $success = chado_insert_record('feature_synonym', $values);
  1434. if (!$success) {
  1435. $this->logMessage("Cannot add alias $alias to feature synonym table.", array(), TRIPAL_WARNING);
  1436. return 0;
  1437. }
  1438. }
  1439. }
  1440. return 1;
  1441. }
  1442. /**
  1443. * Create the feature record & link it to it's analysis
  1444. *
  1445. * @param $organism
  1446. * @param $analysis_id
  1447. * @param $cvterm
  1448. * @param $uniquename
  1449. * @param $name
  1450. * @param $residues
  1451. * @param $is_analysis
  1452. * @param $is_obsolete
  1453. * @param $add_only
  1454. * @param $score
  1455. *
  1456. * @ingroup gff3_loader
  1457. */
  1458. private function loadFeature($organism, $analysis_id, $cvterm, $uniquename,
  1459. $name, $residues, $is_analysis = 'f', $is_obsolete = 'f', $add_only, $score) {
  1460. // Check to see if the feature already exists.
  1461. $feature = NULL;
  1462. $fselect = array(
  1463. 'organism_id' => $organism->organism_id,
  1464. 'uniquename' => $uniquename,
  1465. 'type_id' => $cvterm->cvterm_id
  1466. );
  1467. $columns = array('feature_id', 'name', 'uniquename', 'seqlen', 'organism_id', 'type_id');
  1468. $result = chado_select_record('feature', $columns, $fselect);
  1469. if (count($result) > 0) {
  1470. $feature = $result[0];
  1471. }
  1472. if (strcmp($is_obsolete, 'f')==0 or $is_obsolete == 0) {
  1473. $is_obsolete = 'FALSE';
  1474. }
  1475. if (strcmp($is_obsolete, 't')==0 or $is_obsolete == 1) {
  1476. $is_obsolete = 'TRUE';
  1477. }
  1478. if (strcmp($is_analysis, 'f')==0 or $is_analysis == 0) {
  1479. $is_analysis = 'FALSE';
  1480. }
  1481. if (strcmp($is_analysis, 't')==0 or $is_analysis == 1) {
  1482. $is_analysis = 'TRUE';
  1483. }
  1484. // Insert the feature if it does not exist otherwise perform an update.
  1485. if (!$feature) {
  1486. $values = array(
  1487. 'organism_id' => $organism->organism_id,
  1488. 'name' => $name,
  1489. 'uniquename' => $uniquename,
  1490. 'md5checksum' => md5($residues),
  1491. 'type_id' => $cvterm->cvterm_id,
  1492. 'is_analysis' => $is_analysis,
  1493. 'is_obsolete' => $is_obsolete,
  1494. );
  1495. $feature = (object) chado_insert_record('feature', $values);
  1496. if (!$feature) {
  1497. $this->logMessage("Failed to insert feature '$uniquename' ($cvterm->name).", array(), TRIPAL_WARNING);
  1498. return 0;
  1499. }
  1500. }
  1501. elseif (!$add_only) {
  1502. $values = array(
  1503. 'name' => $name,
  1504. 'md5checksum' => md5($residues),
  1505. 'is_analysis' => $is_analysis,
  1506. 'is_obsolete' => $is_obsolete,
  1507. );
  1508. $match = array(
  1509. 'organism_id' => $organism->organism_id,
  1510. 'uniquename' => $uniquename,
  1511. 'type_id' => $cvterm->cvterm_id,
  1512. );
  1513. $result = chado_update_record('feature', $match, $values);
  1514. if (!$result) {
  1515. $this->logMessage("Failed to update feature '$uniquename' ($cvterm->name).", array(), TRIPAL_WARNING);
  1516. return 0;
  1517. }
  1518. }
  1519. else {
  1520. // The feature exists and we don't want to update it so return
  1521. // a value of 0. This will stop all downstream property additions
  1522. return $feature;
  1523. }
  1524. // Add the analysisfeature entry to the analysisfeature table if
  1525. // it doesn't already exist.
  1526. $af_values = array(
  1527. 'analysis_id' => $analysis_id,
  1528. 'feature_id' => $feature->feature_id
  1529. );
  1530. $afeature = chado_select_record('analysisfeature', array('analysisfeature_id'), $af_values);
  1531. if (count($afeature)==0) {
  1532. // if a score is available then set that to be the significance field
  1533. if (strcmp($score, '.') != 0) {
  1534. $af_values['significance'] = $score;
  1535. }
  1536. if (!chado_insert_record('analysisfeature', $af_values)) {
  1537. $this->logMessage("Could not add analysisfeature record: $analysis_id, $feature->feature_id.", array(), TRIPAL_WARNING);
  1538. }
  1539. }
  1540. else {
  1541. // if a score is available then set that to be the significance field
  1542. $new_vals = array();
  1543. if (strcmp($score, '.')!=0) {
  1544. $new_vals['significance'] = $score;
  1545. }
  1546. else {
  1547. $new_vals['significance'] = '__NULL__';
  1548. }
  1549. if (!$add_only) {
  1550. $ret = chado_update_record('analysisfeature', $af_values, $new_vals);
  1551. if (!$ret) {
  1552. $this->logMessage("Could not update analysisfeature record: $analysis_id, $feature->feature_id.", array(), TRIPAL_WARNING);
  1553. }
  1554. }
  1555. }
  1556. return $feature;
  1557. }
  1558. /**
  1559. * Insert the location of the feature
  1560. *
  1561. * @param $feature
  1562. * @param $organism
  1563. * @param $landmark
  1564. * @param $fmin
  1565. * @param $fmax
  1566. * @param $strand
  1567. * @param $phase
  1568. * @param $is_fmin_partial
  1569. * @param $is_fmax_partial
  1570. * @param $residue_info
  1571. * @param $locgroup
  1572. * @param $landmark_type_id
  1573. * @param $landmark_organism_id
  1574. * @param $create_landmark
  1575. * @param $landmark_is_target
  1576. *
  1577. * @ingroup gff3_loader
  1578. */
  1579. private function loadFeatureLoc($feature, $organism, $landmark, $fmin,
  1580. $fmax, $strand, $phase, $is_fmin_partial, $is_fmax_partial, $residue_info, $locgroup,
  1581. $landmark_type_id = '', $landmark_organism_id = '', $create_landmark = 0,
  1582. $landmark_is_target = 0) {
  1583. $select = array(
  1584. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  1585. 'uniquename' => $landmark,
  1586. );
  1587. if ($landmark_type_id) {
  1588. $select['type_id'] = $landmark_type_id;
  1589. }
  1590. $results = chado_select_record('feature', array('feature_id'), $select);
  1591. $srcfeature = '';
  1592. if (count($results)==0) {
  1593. // so we couldn't find the landmark using the uniquename. Let's try the 'name'.
  1594. // if we return only a single result then we can proceed. Otherwise give an
  1595. $select = array(
  1596. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  1597. 'name' => $landmark,
  1598. );
  1599. if ($landmark_type_id) {
  1600. $select['type_id'] = $landmark_type_id;
  1601. }
  1602. $results = chado_select_record('feature', array('feature_id'), $select);
  1603. if (count($results) == 0) {
  1604. // if the landmark is the target feature in a matched alignment then try one more time to
  1605. // find it by querying any feature with the same uniquename. If we find one then use it.
  1606. if ($landmark_is_target) {
  1607. $select = array('uniquename' => $landmark);
  1608. $results = chado_select_record('feature', array('feature_id'), $select);
  1609. if (count($results) == 1) {
  1610. $srcfeature = $results[0];
  1611. }
  1612. }
  1613. if (!$srcfeature) {
  1614. // we couldn't find the landmark feature, so if the user has requested we create it then do so
  1615. // but only if we have a type id
  1616. if ($create_landmark and $landmark_type_id) {
  1617. $values = array(
  1618. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  1619. 'name' => $landmark,
  1620. 'uniquename' => $landmark,
  1621. 'type_id' => $landmark_type_id
  1622. );
  1623. $results = chado_insert_record('feature', $values);
  1624. if (!$results) {
  1625. $this->logMessage("Cannot find landmark feature: '%landmark', nor could it be inserted.",
  1626. array('%landmark' => $landmark), TRIPAL_WARNING);
  1627. return 0;
  1628. }
  1629. $srcfeature = new stdClass();
  1630. $srcfeature->feature_id = $results['feature_id'];
  1631. }
  1632. else {
  1633. $this->logMessage("Cannot find unique landmark feature: '%landmark'.",
  1634. array('%landmark' => $landmark), TRIPAL_WARNING);
  1635. return 0;
  1636. }
  1637. }
  1638. }
  1639. elseif (count($results) > 1) {
  1640. $this->logMessage("multiple landmarks exist with the name: '%landmark'. Cannot " .
  1641. "resolve which one to use. Cannot add the feature location record.",
  1642. array('%landmark' => $landmark), TRIPAL_WARNING);
  1643. return 0;
  1644. }
  1645. else {
  1646. $srcfeature = $results[0];
  1647. }
  1648. }
  1649. elseif (count($results) > 1) {
  1650. $this->logMessage("multiple landmarks exist with the name: '%landmark'. Cannot " .
  1651. "resolve which one to use. Cannot add the feature location record.",
  1652. array('%landmark' => $landmark, TRIPAL_WARNING));
  1653. return 0;
  1654. }
  1655. else {
  1656. $srcfeature = $results[0];
  1657. }
  1658. // TODO: create an attribute that recognizes the residue_info,locgroup,
  1659. // is_fmin_partial and is_fmax_partial, right now these are
  1660. // hardcoded to be false and 0 below.
  1661. // check to see if this featureloc already exists, but also keep track of the
  1662. // last rank value
  1663. $rank = 0;
  1664. $exists = 0;
  1665. $select = array('feature_id' => $feature->feature_id);
  1666. $options = array(
  1667. 'order_by' => array(
  1668. 'rank' => 'ASC'
  1669. ),
  1670. );
  1671. $locrecs = chado_select_record('featureloc', array('*'), $select, $options);
  1672. foreach ($locrecs as $featureloc) {
  1673. // it is possible for the featureloc->srcfeature_id to be NULL. This can happen if the srcfeature
  1674. // is not known (according to chado table field descriptions). If it's null then just skip this entry
  1675. if (!$featureloc->srcfeature_id) {
  1676. continue;
  1677. }
  1678. $select = array('feature_id' => $featureloc->srcfeature_id);
  1679. $columns = array('feature_id', 'name');
  1680. $locsfeature = chado_select_record('feature', $columns, $select);
  1681. // the source feature name and at least the fmin and fmax must be the same
  1682. // for an update of the featureloc, otherwise we'll insert a new record.
  1683. if (strcmp($locsfeature[0]->name, $landmark)==0 and
  1684. ($featureloc->fmin == $fmin or $featureloc->fmax == $fmax)) {
  1685. $match = array('featureloc_id' => $featureloc->featureloc_id);
  1686. $values = array();
  1687. $exists = 1;
  1688. if ($featureloc->fmin != $fmin) {
  1689. $values['fmin'] = $fmin;
  1690. }
  1691. if ($featureloc->fmax != $fmax) {
  1692. $values['fmax'] = $fmax;
  1693. }
  1694. if ($featureloc->strand != $strand) {
  1695. $values['strand'] = $strand;
  1696. }
  1697. if (count($values) > 0) {
  1698. chado_update_record('featureloc', $match, $values);
  1699. }
  1700. }
  1701. $rank = $featureloc->rank + 1;
  1702. }
  1703. if (!$exists) {
  1704. // this feature location is new so add it
  1705. if (strcmp($is_fmin_partial, 'f')==0 or !$is_fmin_partial) {
  1706. $is_fmin_partial = 'FALSE';
  1707. }
  1708. elseif (strcmp($is_fmin_partial, 't')==0 or $is_fmin_partial = 1) {
  1709. $is_fmin_partial = 'TRUE';
  1710. }
  1711. if (strcmp($is_fmax_partial, 'f')==0 or !$is_fmax_partial) {
  1712. $is_fmax_partial = 'FALSE';
  1713. }
  1714. elseif (strcmp($is_fmax_partial, 't')==0 or $is_fmax_partial = 1) {
  1715. $is_fmax_partial = 'TRUE';
  1716. }
  1717. $values = array(
  1718. 'feature_id' => $feature->feature_id,
  1719. 'srcfeature_id' => $srcfeature->feature_id,
  1720. 'fmin' => $fmin,
  1721. 'is_fmin_partial' => $is_fmin_partial,
  1722. 'fmax' => $fmax,
  1723. 'is_fmax_partial' => $is_fmax_partial,
  1724. 'strand' => $strand,
  1725. 'residue_info' => $residue_info,
  1726. 'locgroup' => $locgroup,
  1727. 'rank' => $rank
  1728. );
  1729. if ($phase) {
  1730. $values['phase'] = $phase;
  1731. }
  1732. $success = chado_insert_record('featureloc', $values);
  1733. if (!$success) {
  1734. throw new Exception("Failed to insert featureloc.");
  1735. }
  1736. }
  1737. return 1;
  1738. }
  1739. /**
  1740. * Load a preoprty (featurepop) for the feature
  1741. *
  1742. * @param $feature
  1743. * @param $property
  1744. * @param $value
  1745. *
  1746. * @ingroup gff3_loader
  1747. */
  1748. private function loadProperty($feature, $property, $value) {
  1749. // first make sure the cvterm exists. if not, then add it
  1750. $select = array(
  1751. 'name' => $property,
  1752. 'cv_id' => array(
  1753. 'name' => 'feature_property',
  1754. ),
  1755. );
  1756. $result = chado_select_record('cvterm', array('*'), $select);
  1757. // if we don't have a property like this already, then add it otherwise, just return
  1758. if (count($result) == 0) {
  1759. $term = array(
  1760. 'id' => "null:$property",
  1761. 'name' => $property,
  1762. 'namespace' => 'feature_property',
  1763. 'is_obsolete' => 0,
  1764. 'cv_name' => 'feature_property',
  1765. 'is_relationship' => FALSE
  1766. );
  1767. $cvterm = (object)chado_insert_cvterm($term, array('update_existing' => FALSE));
  1768. if (!$cvterm) {
  1769. $this->logMessage("Cannot add cvterm, $property.", array(), TRIPAL_WARNING);
  1770. return 0;
  1771. }
  1772. }
  1773. else {
  1774. $cvterm = $result[0];
  1775. }
  1776. // check to see if the property already exists for this feature
  1777. // if it does but the value is unique then increment the rank and add it.
  1778. // if the value is not unique then don't add it.
  1779. $add = 1;
  1780. $rank = 0;
  1781. $select = array(
  1782. 'feature_id' => $feature->feature_id,
  1783. 'type_id' => $cvterm->cvterm_id,
  1784. );
  1785. $options = array(
  1786. 'order_by' => array(
  1787. 'rank' => 'ASC',
  1788. ),
  1789. );
  1790. $results = chado_select_record('featureprop', array('*'), $select, $options);
  1791. foreach ($results as $prop) {
  1792. if (strcmp($prop->value, $value)==0) {
  1793. $add = NULL; // don't add it, it already exists
  1794. }
  1795. $rank = $prop->rank + 1;
  1796. }
  1797. // add the property if we pass the check above
  1798. if ($add) {
  1799. $values = array(
  1800. 'feature_id' => $feature->feature_id,
  1801. 'type_id' => $cvterm->cvterm_id,
  1802. 'value' => $value,
  1803. 'rank' => $rank,
  1804. );
  1805. $result = chado_insert_record('featureprop', $values);
  1806. if (!$result) {
  1807. $this->logMessage("cannot add featureprop, $property.", array(), TRIPAL_WARNING);
  1808. }
  1809. }
  1810. }
  1811. /**
  1812. * Load the FASTA sequences at the bottom of a GFF3 file
  1813. *
  1814. * @param $fh
  1815. * @param $interval
  1816. * @param $num_read
  1817. * @param $line_num
  1818. * @param $filesize
  1819. *
  1820. * @ingroup gff3_loader
  1821. */
  1822. private function loadFasta($fh, $interval, &$num_read, &$line_num, $filesize) {
  1823. $this->logMessage("Loading FASTA sequences...");
  1824. $residues = '';
  1825. $id = NULL;
  1826. // iterate through the remaining lines of the file
  1827. while ($line = fgets($fh)) {
  1828. $line_num++;
  1829. $size = drupal_strlen($line);
  1830. $this->addItemsHandled($size);
  1831. $num_read += $size;
  1832. $line = trim($line);
  1833. // if we encounter a definition line then get the name, uniquename,
  1834. // accession and relationship subject from the definition line
  1835. if (preg_match('/^>/', $line)) {
  1836. // if we are beginning a new sequence then save to the database the last one we just finished.
  1837. if ($id) {
  1838. $values = array('uniquename' => $id);
  1839. $result = chado_select_record('tripal_gff_temp', array('*'), $values);
  1840. if (count($result) == 0) {
  1841. $this->logMessage('Cannot find feature to assign FASTA sequence: %uname.',
  1842. array('%uname' => $id), TRIPAL_WARNING);
  1843. }
  1844. else {
  1845. // if we have a feature then add the residues
  1846. $feature = $result[0];
  1847. $values = array(
  1848. 'residues' => $residues,
  1849. 'seqlen' => strlen($residues)
  1850. );
  1851. $match = array('feature_id' => $feature->feature_id);
  1852. chado_update_record('feature', $match, $values);
  1853. }
  1854. }
  1855. // get the feature ID for this ID from the tripal_gff_temp table. It
  1856. // should be the name up to the first space
  1857. $id = preg_replace('/^>([^\s]+).*$/', '\1', $line);
  1858. $residues = '';
  1859. }
  1860. else {
  1861. $residues .= trim($line);
  1862. }
  1863. }
  1864. // add in the last sequence
  1865. $values = array('uniquename' => $id);
  1866. $result = chado_select_record('tripal_gff_temp', array('*'), $values);
  1867. if (count($result) == 0) {
  1868. $this->logMessage('Cannot find feature to assign FASTA sequence: %uname.',
  1869. array('%uname' => $id), TRIPAL_WARNING);
  1870. }
  1871. else {
  1872. // if we have a feature then add the residues
  1873. $feature = $result[0];
  1874. $values = array(
  1875. 'residues' => $residues,
  1876. 'seqlen' => strlen($residues)
  1877. );
  1878. $match = array('feature_id' => $feature->feature_id);
  1879. chado_update_record('feature', $match, $values);
  1880. }
  1881. }
  1882. /**
  1883. * Load the target attribute of a gff3 record
  1884. *
  1885. * @param $feature
  1886. * @param $tags
  1887. * @param $target_organism_id
  1888. * @param $target_type
  1889. * @param $create_target
  1890. * @param $attr_locgroup
  1891. *
  1892. * @ingroup gff3_loader
  1893. */
  1894. private function loadTarget($feature, $tags, $target_organism_id, $target_type, $create_target, $attr_locgroup) {
  1895. // format is: "target_id start end [strand]", where strand is optional and may be "+" or "-"
  1896. $matched = preg_match('/^(.*?)\s+(\d+)\s+(\d+)(\s+[\+|\-])*$/', trim($tags['Target'][0]), $matches);
  1897. // the organism and type of the target may also be specified as an attribute. If so, then get that
  1898. // information
  1899. $gff_target_organism = array_key_exists('target_organism', $tags) ? $tags['target_organism'][0] : '';
  1900. $gff_target_type = array_key_exists('target_type', $tags) ? $tags['target_type'][0] : '';
  1901. // if we have matches and the Target is in the correct format then load the alignment
  1902. if ($matched) {
  1903. $target_feature = $matches[1];
  1904. $start = $matches[2];
  1905. $end = $matches[3];
  1906. // if we have an optional strand, convert it to a numeric value.
  1907. if ($matches[4]) {
  1908. if (preg_match('/^\+$/', trim($matches[4]))) {
  1909. $target_strand = 1;
  1910. }
  1911. elseif (preg_match('/^\-$/', trim($matches[4]))) {
  1912. $target_strand = -1;
  1913. }
  1914. else {
  1915. $target_strand = 0;
  1916. }
  1917. }
  1918. else {
  1919. $target_strand = 0;
  1920. }
  1921. $target_fmin = $start - 1;
  1922. $target_fmax = $end;
  1923. if ($end < $start) {
  1924. $target_fmin = $end - 1;
  1925. $target_fmax = $start;
  1926. }
  1927. // default the target organism to be the value passed into the function, but if the GFF
  1928. // file species the target organism then use that instead.
  1929. $t_organism_id = $target_organism_id;
  1930. if ($gff_target_organism) {
  1931. // get the genus and species
  1932. $success = preg_match('/^(.*?):(.*?)$/', $gff_target_organism, $matches);
  1933. if ($success) {
  1934. $values = array(
  1935. 'genus' => $matches[1],
  1936. 'species' => $matches[2],
  1937. );
  1938. $torganism = chado_select_record('organism', array('organism_id'), $values);
  1939. if (count($torganism) == 1) {
  1940. $t_organism_id = $torganism[0]->organism_id;
  1941. }
  1942. else {
  1943. $this->logMessage("Cannot find organism for target %target.",
  1944. array('%target' => $gff_target_organism), TRIPAL_WARNING);
  1945. $t_organism_id = '';
  1946. }
  1947. }
  1948. else {
  1949. $this->logMessage("The target_organism attribute is improperly formatted: %target. " .
  1950. "It should be target_organism=genus:species.",
  1951. array('%target' => $gff_target_organism), TRIPAL_WARNING);
  1952. $t_organism_id = '';
  1953. }
  1954. }
  1955. // default the target type to be the value passed into the function, but if the GFF file
  1956. // species the target type then use that instead
  1957. $t_type_id = '';
  1958. if ($target_type) {
  1959. $values = array(
  1960. 'name' => $target_type,
  1961. 'cv_id' => array(
  1962. 'name' => 'sequence',
  1963. )
  1964. );
  1965. $type = chado_select_record('cvterm', array('cvterm_id'), $values);
  1966. if (count($type) == 1) {
  1967. $t_type_id = $type[0]->cvterm_id;
  1968. }
  1969. else {
  1970. throw new Exception(t("The target type does not exist in the sequence ontology: %type. ",
  1971. array('%type' => $target_type)));
  1972. }
  1973. }
  1974. if ($gff_target_type) {
  1975. $values = array(
  1976. 'name' => $gff_target_type,
  1977. 'cv_id' => array(
  1978. 'name' => 'sequence',
  1979. )
  1980. );
  1981. // get the cvterm_id for the target type
  1982. $type = chado_select_record('cvterm', array('cvterm_id'), $values);
  1983. if (count($type) == 1) {
  1984. $t_type_id = $type[0]->cvterm_id;
  1985. }
  1986. else {
  1987. // check to see if this is a synonym
  1988. $sql = "
  1989. SELECT CVTS.cvterm_id
  1990. FROM {cvtermsynonym} CVTS
  1991. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = CVTS.cvterm_id
  1992. INNER JOIN {cv} CV ON CV.cv_id = CVT.cv_id
  1993. WHERE CV.name = 'sequence' and CVTS.synonym = :synonym
  1994. ";
  1995. $synonym = chado_query($sql, array(':synonym' => $gff_target_type))->fetchObject();
  1996. if ($synonym) {
  1997. $t_type_id = $synonym->cvterm_id;
  1998. }
  1999. else {
  2000. $this->logMessage("The target_type attribute does not exist in the sequence ontology: %type.",
  2001. array('%type' => $gff_target_type), TRIPAL_WARNING);
  2002. $t_type_id = '';
  2003. }
  2004. }
  2005. }
  2006. // we want to add a featureloc record that uses the target feature as the srcfeature (landmark)
  2007. // and the landmark as the feature.
  2008. $this->loadFeatureLoc($feature, $organism, $target_feature, $target_fmin,
  2009. $target_fmax, $target_strand, $phase, $attr_fmin_partial, $attr_fmax_partial, $attr_residue_info,
  2010. $attr_locgroup, $t_type_id, $t_organism_id, $create_target, TRUE);
  2011. }
  2012. // the target attribute is not correctly formatted
  2013. else {
  2014. $this->logMessage("Could not add 'Target' alignment as it is improperly formatted: '%target'",
  2015. array('%target' => $tags['Target'][0]), TRIPAL_ERROR);
  2016. }
  2017. }
  2018. }