tripal_feature.gff_loader.inc 86 KB

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