tripal_chado.gff_loader.inc 82 KB

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