tripal_chado.gff_loader.inc 86 KB

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