tripal_feature.gff_loader.inc 72 KB

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