GFF3Importer.inc 82 KB

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