GFF3Importer.inc 89 KB

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