tripal_chado.gff_loader.inc 82 KB

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