tripal_feature.gff_loader.inc 76 KB

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