GFF3Importer.inc 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677
  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 = 'chado_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 = ['gff', '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.';
  27. /**
  28. * The title that should appear above the upload button.
  29. */
  30. public static $upload_title = 'GFF3 File';
  31. /**
  32. * Text that should appear on the button at the bottom of the importer
  33. * form.
  34. */
  35. public static $button_text = 'Import GFF3 file';
  36. /**
  37. * The lines from the ##sequence-region at the top of the GFF
  38. */
  39. private $seq_region_headers = [];
  40. /**
  41. * The path to the GFF3 file.
  42. */
  43. private $gff_file = NULL;
  44. /**
  45. * The file handle for the GFF3 file.
  46. */
  47. private $gff_file_h = NULL;
  48. /**
  49. * The organism ID for this GFF file.
  50. */
  51. private $organism_id = NULL;
  52. /**
  53. * The organism ChadoRecord object that corresponds to the $organism_id value.
  54. */
  55. private $organism = NULL;
  56. /**
  57. * An array of organism records for quick lookup.
  58. */
  59. private $organism_lookup = [];
  60. /**
  61. * The analysis ID for this GFF file
  62. */
  63. private $analysis_id = NULL;
  64. /**
  65. * The analysis ChadoRecord object that corresponds to the $analysis_id value.
  66. */
  67. private $analysis = NULL;
  68. /**
  69. * A flag indicating if only new items should be added (no updates)
  70. */
  71. private $add_only = NULL;
  72. /**
  73. * A flag indicting if only existing items should be updated.
  74. */
  75. private $update = TRUE;
  76. /**
  77. * If the GFF file contains a 'Target' attribute then the feature and the
  78. * target will have an alignment created, but to find the proper target
  79. * feature the target organism must also be known. If different from the
  80. * organism specified for the GFF file, then use this argument to specify
  81. * the target organism. Only use this argument if all target sequences
  82. * belong to the same species. If the targets in the GFF file belong to
  83. * multiple different species then the organism must be specified using the
  84. * 'target_organism=genus:species' attribute in the GFF file. Default is
  85. * NULL.
  86. */
  87. private $target_organism_id = NULL;
  88. /**
  89. * If the GFF file contains a 'Target' attribute then the feature and the
  90. * target will have an alignment created, but to find the proper target
  91. * feature the target organism must also be known. This can be used to
  92. * specify the target feature type to help with identification of the
  93. * target feature. Only use this argument if all target sequences types are
  94. * the same. If the targets are of different types then the type must be
  95. * specified using the 'target_type=type' attribute in the GFF file. This
  96. * must be a valid Sequence Ontology (SO) term. Default is NULL
  97. */
  98. private $target_type = NULL;
  99. /**
  100. * A flag indicating if the target feature should be created. If FALSE
  101. * then it should already exist.
  102. */
  103. private $create_target = FALSE;
  104. /**
  105. * Set this to the line in the GFF file where importing should start. This
  106. * is useful for testing and debugging GFF files that may have problems and
  107. * you want to start at a particular line to speed testing. Default = 1
  108. */
  109. private $start_line = 1;
  110. /**
  111. * During parsing of the GFF file this keeps track of the current line
  112. * number.
  113. */
  114. private $current_line = 0;
  115. /**
  116. * A Sequence Ontology term name for the landmark sequences in the GFF
  117. * file (e.g. 'chromosome'), if the GFF file contains a '##sequence-region'
  118. * line that describes the landmark sequences. Default = ''
  119. */
  120. private $landmark_type = '';
  121. /**
  122. * The ChadoRecord object for the landmark type cvterm.
  123. */
  124. private $landmark_cvterm = NULL;
  125. /**
  126. * Regular expression to pull out the mRNA name.
  127. */
  128. private $re_mrna = '';
  129. /**
  130. * Regular expression to pull out the protein name.
  131. */
  132. private $re_protein = '';
  133. /**
  134. * A flag that indicates if a protein record should be created.
  135. * @var integer
  136. */
  137. private $skip_protein = 0;
  138. /**
  139. * Sometimes lines in the GFF file are missing the required ID attribute
  140. * that specifies the unique name of the feature. If so, you may specify
  141. * the name of an existing attribute to use for the ID.
  142. */
  143. private $alt_id_attr = '';
  144. /**
  145. * The Tripal GFF loader supports the "organism" attribute. This allows
  146. * features of a different organism to be aligned to the landmark sequence
  147. * of another species. The format of the attribute is
  148. * "organism=[genus]:[species]", where [genus] is the organism's genus and
  149. * [species] is the species name. Check this box to automatically add the
  150. * organism to the database if it does not already exists. Otherwise lines
  151. * with an oraganism attribute where the organism is not present in the
  152. * database will be skipped.
  153. */
  154. private $create_organism = FALSE;
  155. /**
  156. * Holds mapping of DB names to DB ids.
  157. */
  158. private $db_lookup = [];
  159. /**
  160. * Holds a mapping of Dbxref names to ids.
  161. */
  162. private $dbxref_lookup = [];
  163. /**
  164. * Holds a mapping of Dbxref names to cvterm ids.
  165. */
  166. private $cvterm_lookup = [];
  167. /**
  168. * Holds a mapping of synonymns to ids.
  169. */
  170. private $synonym_lookup = [];
  171. /**
  172. * Maps parents to their children and contains the ranks of the children.
  173. */
  174. private $parent_lookup = [];
  175. /**
  176. * An array that stores CVterms that have been looked up so we don't have
  177. * to do the database query every time.
  178. */
  179. private $feature_cvterm_lookup = [];
  180. /**
  181. * Holds a mapping of cvterms to their aliases that are used in the
  182. * GFF3 file.
  183. */
  184. private $feature_cvterm_aliases = [];
  185. /**
  186. * An array that stores CVterms that have been looked up so we don't have
  187. * to do the database query every time.
  188. */
  189. private $featureprop_cvterm_lookup = [];
  190. /**
  191. * Holds the CV term for the "exact" synonym.
  192. */
  193. private $exact_syn = NULL;
  194. /**
  195. * Holds the object for the null publication record.
  196. */
  197. private $null_pub = NULL;
  198. /**
  199. * The list of features from the GFF3 file. Each element is an
  200. * associative array of the columns from the GFF3 file, with the attribute
  201. * field being an associative array of key/value pairs.
  202. */
  203. private $features = [];
  204. /**
  205. * An associatiave array containing the pointers to the FASTA sequences
  206. * in the GFF file. We don't want to load these into memory as they
  207. * may be too big!
  208. */
  209. private $residue_index = [];
  210. /**
  211. * An array that stores landmarks objects. Landmarks should be inserted
  212. * first if they don't already exist.
  213. */
  214. private $landmarks = [];
  215. /**
  216. * A controlled vocabulary ChadoRecord object. This is the CV that will be
  217. * used to for feature properties.
  218. */
  219. private $feature_prop_cv = NULL;
  220. /**
  221. * A controlled vocabulary ChadoRecord object. This is the CV that will be
  222. * used to for feature properties.
  223. */
  224. private $feature_cv = NULL;
  225. /**
  226. * @see TripalImporter::form()
  227. */
  228. public function form($form, &$form_state) {
  229. // get the list of organisms
  230. $sql = "SELECT * FROM {organism} ORDER BY genus, species";
  231. $org_rset = chado_query($sql);
  232. $organisms = [];
  233. $organisms[''] = '';
  234. while ($organism = $org_rset->fetchObject()) {
  235. $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
  236. }
  237. $form['organism_id'] = [
  238. '#title' => t('Existing Organism'),
  239. '#type' => 'select',
  240. '#description' => t("Choose an existing organism to which the entries in the GFF file will be associated."),
  241. '#required' => TRUE,
  242. '#options' => $organisms,
  243. ];
  244. $form['create_organism'] = [
  245. '#type' => 'checkbox',
  246. '#title' => t('Create organism'),
  247. '#required' => FALSE,
  248. '#description' => t('The Tripal GFF loader supports the "organism" attribute. This allows features of a
  249. different organism to be aligned to the landmark sequence. The format of the
  250. attribute is "organism=[genus]:[species]", where [genus] is the organism\'s genus and [species] is the
  251. species name. Check this box to automatically add the organism to the database if it does not already exists.
  252. Otherwise lines with an organism attribute where the organism is not present in the database will be skipped.'),
  253. ];
  254. $form['landmark_type'] = [
  255. '#title' => t('Landmark Type'),
  256. '#type' => 'textfield',
  257. '#description' => t("Optional. Use this field to specify a Sequence Ontology type
  258. for the landmark sequences in the GFF fie (e.g. 'chromosome'). This is only needed if
  259. the landmark features (first column of the GFF3 file) are not already in the database.."),
  260. ];
  261. $form['proteins'] = [
  262. '#type' => 'fieldset',
  263. '#title' => t('Proteins'),
  264. '#collapsible' => TRUE,
  265. '#collapsed' => FALSE,
  266. ];
  267. $form['proteins']['skip_protein'] = [
  268. '#type' => 'checkbox',
  269. '#title' => t('Skip automatic protein creation'),
  270. '#required' => FALSE,
  271. '#description' => t('The GFF loader will automatically create a protein feature for each transcript in the GFF file if a protein feature is missing in the GFF file. Check this box to disable this functionality. Protein features that are specifically present in the GFF will always be created.'),
  272. '#default_value' => 0,
  273. ];
  274. $form['proteins']['re_mrna'] = [
  275. '#type' => 'textfield',
  276. '#title' => t('Optional. Regular expression for the mRNA name'),
  277. '#required' => FALSE,
  278. '#description' => t('If automatic protein creation is enabled, then by default the loader will give each protein a name based on the name of the corresponding mRNA followed by the "-protein" suffix.
  279. If you want to customize the name of the created protein, you can enter a regular expression that will extract portions of
  280. the mRNA unique name. For example, for a
  281. mRNA with a unique name finishing by -RX (e.g. SPECIES0000001-RA),
  282. the regular expression would be, "^(.*?)-R([A-Z]+)$". Elements surrounded by parentheses are captured as backreferences and can be used for replacement.' ),
  283. ];
  284. $form['proteins']['re_protein'] = [
  285. '#type' => 'textfield',
  286. '#title' => t('Optional. Replacement string for the protein name'),
  287. '#required' => FALSE,
  288. '#description' => t('If a regular expression is used to specify a protein name you can use the backreference tokens to extract the portion of the mRNA name that you want to use for a protein.
  289. You use a dollar sign followed by a number to indicate the backreferences. For example: "$1-P$2".'),
  290. ];
  291. $form['targets'] = [
  292. '#type' => 'fieldset',
  293. '#title' => t('Targets'),
  294. '#collapsible' => TRUE,
  295. '#collapsed' => FALSE,
  296. ];
  297. $form['targets']['adesc'] = [
  298. '#markup' => t("When alignments are represented in the GFF file (e.g. such as
  299. alignments of cDNA sequences to a whole genome, or blast matches), they are
  300. represented using two feature types: 'match' (or cDNA_match, EST_match, etc.)
  301. and 'match_part'. These features may also have a 'Target' attribute to
  302. specify the sequence that is being aligned.
  303. However, the organism to which the aligned sequence belongs may not be present in the
  304. GFF file. Here you can specify the organism and feature type of the target sequences.
  305. The options here will apply to all targets unless the organism and type are explicity
  306. set in the GFF file using the 'target_organism' and 'target_type' attributes."),
  307. ];
  308. $form['targets']['target_organism_id'] = [
  309. '#title' => t('Target Organism'),
  310. '#type' => t('select'),
  311. '#description' => t("Optional. Choose the organism to which target sequences belong.
  312. Select this only if target sequences belong to a different organism than the
  313. one specified above. And only choose an organism here if all of the target sequences
  314. belong to the same species. If the targets in the GFF file belong to multiple
  315. different species then the organism must be specified using the 'target_organism=genus:species'
  316. attribute in the GFF file."),
  317. '#options' => $organisms,
  318. ];
  319. $form['targets']['target_type'] = [
  320. '#title' => t('Target Type'),
  321. '#type' => t('textfield'),
  322. '#description' => t("Optional. If the unique name for a target sequence is not unique (e.g. a protein
  323. and an mRNA have the same name) then you must specify the type for all targets in the GFF file. If
  324. the targets are of different types then the type must be specified using the 'target_type=type' attribute
  325. in the GFF file. This must be a valid Sequence Ontology (SO) term."),
  326. ];
  327. $form['targets']['create_target'] = [
  328. '#type' => 'checkbox',
  329. '#title' => t('Create Target'),
  330. '#required' => FALSE,
  331. '#description' => t("If the target feature cannot be found, create one using the organism and type specified above, or
  332. using the 'target_organism' and 'target_type' fields specified in the GFF file. Values specified in the
  333. GFF file take precedence over those specified above."),
  334. ];
  335. // Advanced Options
  336. $form['advanced'] = [
  337. '#type' => 'fieldset',
  338. '#title' => t('Additional Options'),
  339. '#collapsible' => TRUE,
  340. '#collapsed' => FALSE,
  341. ];
  342. $form['advanced']['line_number'] = [
  343. '#type' => 'textfield',
  344. '#title' => t('Start Line Number'),
  345. '#description' => t('Enter the line number in the GFF file where you would like to begin processing. The
  346. first line is line number 1. This option is useful for examining loading problems with large GFF files.'),
  347. '#size' => 10,
  348. ];
  349. $form['advanced']['alt_id_attr'] = [
  350. '#title' => t('ID Attribute'),
  351. '#type' => t('textfield'),
  352. '#description' => t("Optional. Sometimes lines in the GFF file are missing the
  353. required ID attribute that specifies the unique name of the feature, but there
  354. may be another attribute that can uniquely identify the feature. If so,
  355. you may specify the name of the attribute to use for the name."),
  356. ];
  357. return $form;
  358. }
  359. /**
  360. * @see TripalImporter::formValidate()
  361. */
  362. public function formValidate($form, &$form_state) {
  363. $organism_id = $form_state['values']['organism_id'];
  364. $target_organism_id = $form_state['values']['target_organism_id'];
  365. $target_type = trim($form_state['values']['target_type']);
  366. $create_target = $form_state['values']['create_target'];
  367. $create_organism = $form_state['values']['create_organism'];
  368. $add_only = $form_state['values']['add_only'];
  369. $update = $form_state['values']['update'];
  370. $refresh = 0; //$form_state['values']['refresh'];
  371. $remove = 0; //$form_state['values']['remove'];
  372. $line_number = trim($form_state['values']['line_number']);
  373. $landmark_type = trim($form_state['values']['landmark_type']);
  374. $alt_id_attr = trim($form_state['values']['alt_id_attr']);
  375. $re_mrna = trim($form_state['values']['re_mrna']);
  376. $re_protein = trim($form_state['values']['re_protein']);
  377. // @coder-ignore: there are no functions being called here
  378. if (($add_only AND ($update OR $refresh OR $remove)) OR
  379. ($update AND ($add_only OR $refresh OR $remove)) OR
  380. ($refresh AND ($update OR $add_only OR $remove)) OR
  381. ($remove AND ($update OR $refresh OR $add_only))) {
  382. form_set_error('add_only', t("Please select only one checkbox from the import options section"));
  383. }
  384. if ($line_number and !is_numeric($line_number) or $line_number < 0) {
  385. form_set_error('line_number', t("Please provide an integer line number greater than zero."));
  386. }
  387. if (!($re_mrna and $re_protein) and ($re_mrna or $re_protein)) {
  388. form_set_error('re_uname', t("You must provide both a regular expression for mRNA and a replacement string for protein"));
  389. }
  390. // check the regular expression to make sure it is valid
  391. set_error_handler(function () {
  392. }, E_WARNING);
  393. $result_re = preg_match("/" . $re_mrna . "/", NULL);
  394. $result = preg_replace("/" . $re_mrna . "/", $re_protein, NULL);
  395. restore_error_handler();
  396. if ($result_re === FALSE) {
  397. form_set_error('re_mrna', 'Invalid regular expression.');
  398. }
  399. else {
  400. if ($result === FALSE) {
  401. form_set_error('re_protein', 'Invalid replacement string.');
  402. }
  403. }
  404. }
  405. /**
  406. * @see TripalImporter::run()
  407. */
  408. public function run() {
  409. $arguments = $this->arguments['run_args'];
  410. $this->gff_file = $this->arguments['files'][0]['file_path'];
  411. // Set the private member variables of this class using the loader inputs.
  412. $this->organism_id = $arguments['organism_id'];
  413. $this->analysis_id = $arguments['analysis_id'];
  414. $this->add_only = $arguments['add_only'];
  415. $this->update = $arguments['update'];
  416. $this->target_organism_id = $arguments['target_organism_id'];
  417. $this->target_type = $arguments['target_type'];
  418. $this->create_target = $arguments['create_target'];
  419. $this->start_line = $arguments['line_number'];
  420. $this->landmark_type = $arguments['landmark_type'];
  421. $this->alt_id_attr = $arguments['alt_id_attr'];
  422. $this->create_organism = $arguments['create_organism'];
  423. $this->re_mrna = $arguments['re_mrna'];
  424. $this->re_protein = $arguments['re_protein'];
  425. $this->skip_protein = $arguments['skip_protein'];
  426. // Check to see if the file is located local to Drupal
  427. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $this->gff_file;
  428. if (!file_exists($dfile)) {
  429. $this->gff_file = $dfile;
  430. }
  431. // If the file is not local to Drupal check if it exists on the system.
  432. else if (!file_exists($this->gff_file)) {
  433. throw new Exception(t("Cannot find the file: !file", ['!file' => $this->gff_file]));
  434. }
  435. // Open the GFF3 file.
  436. $this->logMessage("Opening !gff_file", ['!gff_file' => $this->gff_file]);
  437. $this->gff_file_h = fopen($this->gff_file, 'r');
  438. if (!$this->gff_file_h) {
  439. throw new Exception(t("Cannot open file: !file", ['!file' => $this->gff_file]));
  440. }
  441. // Get the feature property CV object
  442. $this->feature_prop_cv = new ChadoRecord('cv');
  443. $this->feature_prop_cv->setValues(['name' => 'feature_property']);
  444. $num_found = $this->feature_prop_cv->find();
  445. if ($num_found == 0) {
  446. throw new Exception(t("Cannot find the 'feature_property' ontology'", []));
  447. }
  448. // Get the sequence CV object.
  449. $this->feature_cv = new ChadoRecord('cv');
  450. $this->feature_cv->setValues(['name' => 'sequence']);
  451. $num_found = $this->feature_cv->find();
  452. if ($num_found == 0) {
  453. throw new Exception(t("Cannot find the 'sequence' ontology'", []));
  454. }
  455. // Get the organism object.
  456. $this->organism = new ChadoRecord('organism');
  457. $this->organism->setValues(['organism_id' => $this->organism_id]);
  458. $num_found = $this->organism->find();
  459. if ($num_found == 0) {
  460. throw new Exception(t("Cannot find the specified organism for this GFF3 file."));
  461. }
  462. // Get the analysis object.
  463. $this->analysis = new ChadoRecord('analysis');
  464. $this->analysis->setValues(['analysis_id' => $this->analysis_id]);
  465. $num_found = $this->analysis->find();
  466. if ($num_found == 0) {
  467. throw new Exception(t("Cannot find the specified organism for this GFF3 file."));
  468. }
  469. // If a landmark type was provided then get that object.
  470. if ($this->landmark_type) {
  471. $this->landmark_cvterm = new ChadoRecord('cvterm');
  472. $this->landmark_cvterm->setValues([
  473. 'cv_id' => $this->feature_cv->getValue('cv_id'),
  474. 'name' => $this->landmark_type,
  475. ]);
  476. $num_found = $this->landmark_cvterm->find();
  477. if ($num_found == 0) {
  478. throw new Exception(t('Cannot find landmark feature type \'%landmark_type\'.', ['%landmark_type' => $this->landmark_type]));
  479. }
  480. }
  481. // Load the GFF3.
  482. $this->logMessage("Step 1: Preloading GFF3 file... ");
  483. $this->parseGFF3();
  484. // Prep the database for necessary records.
  485. $this->prepSynonms();
  486. $this->prepNullPub();
  487. $this->prepDBs();
  488. $this->logMessage("Step 2: Load landmarks sequences... ");
  489. $this->insertLandmarks();
  490. $this->logMessage("Step 3: Find existing features... ");
  491. $this->findFeatures();
  492. $this->logMessage("Step 4: Prepare for any updates ... ");
  493. $this->deleteFeatureData();
  494. $this->logMessage("Step 5: Loading !num_features features... ",
  495. ['!num_features' => count(array_keys($this->features))]);
  496. $this->insertFeatures();
  497. $this->logMessage("Step 6: Get new feature IDs... ");
  498. $this->findFeatures();
  499. $this->logMessage("Step 7: Loading locations... ");
  500. $this->insertFeatureLocs();
  501. $this->logMessage("Step 8: Loading properties... ");
  502. $this->insertFeatureProps();
  503. $this->logMessage("Step 9: Finding synonyms (aliases)... ");
  504. $this->findSynonyms();
  505. $this->logMessage("Step 10: Loading synonsyms (aliases)... ");
  506. $this->insertSynonyms();
  507. $this->logMessage("Step 11: Loading feature synonyms (aliases)... ");
  508. $this->insertFeatureSynonyms();
  509. $this->logMessage("Step 12: Finding existing cross references... ");
  510. $this->findDbxrefs();
  511. $this->logMessage("Step 13: Loading cross references... ");
  512. $this->insertDbxrefs();
  513. $this->logMessage("Step 14: Retrieving loaded cross references... ");
  514. $this->findDbxrefs();
  515. $this->logMessage("Step 15: Loading feature cross references... ");
  516. $this->insertFeatureDbxrefs();
  517. $this->logMessage("Step 16: Loading feature ontology terms... ");
  518. $this->insertFeatureCVterms();
  519. $this->logMessage("Step 17: Associate child-parent relationships... ");
  520. $this->findChildRanks();
  521. $this->insertFeatureParents();
  522. $this->logMessage("Step 18: Loading 'derives_from' relationships... ");
  523. $this->insertFeatureDerivesFrom();
  524. $this->logMessage("Step 19: Loading Targets... ");
  525. // TODO: Target (target_organism & target_type)
  526. $this->logMessage("Step 20: Adding any missing proteins... ");
  527. // TODO: protein records.
  528. // TODO: handle is_circular (it may just need to be a property).
  529. if (!empty($this->residue_index)) {
  530. $this->logMessage("Step 21: Adding sequences if available... ");
  531. $this->insertFeatureSeqs();
  532. }
  533. }
  534. /**
  535. * Load a controlled vocabulary term.
  536. *
  537. * This method first checks if the term has already been loaded in the
  538. * feature_cvterm_lookup array, which helps a lot with performance.
  539. *
  540. * @param $type
  541. * @param $cv_id
  542. *
  543. * @ingroup gff3_loader
  544. */
  545. private function getCvtermID($type, $cv_id = NULL, $is_prop_type = FALSE) {
  546. if (!isset($cv_id)) {
  547. $cv_id = $this->feature_cv->getValue('cv_id');
  548. }
  549. if ($is_prop_type and array_key_exists(strtolower($type), $this->featureprop_cvterm_lookup)) {
  550. return $this->featureprop_cvterm_lookup[strtolower($type)];
  551. }
  552. elseif (array_key_exists(strtolower($type), $this->feature_cvterm_lookup)) {
  553. return $this->feature_cvterm_lookup[strtolower($type)];
  554. }
  555. $sel_cvterm_sql = "
  556. SELECT CVT.cvterm_id
  557. FROM {cvterm} CVT
  558. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  559. WHERE CVT.cv_id = {$cv_id} and
  560. (lower(CVT.name) = lower(:name) or lower(CVTS.synonym) = lower(:synonym))
  561. ";
  562. $result = chado_query($sel_cvterm_sql, [
  563. ':name' => $type,
  564. ':synonym' => $type,
  565. ]);
  566. $cvterm = $result->fetchObject() ?? NULL;
  567. if ($cvterm) {
  568. $cvterm = chado_get_cvterm(array('cvterm_id' => $cvterm->cvterm_id)) ?? NULL;
  569. }
  570. if ($is_prop_type) {
  571. $this->featureprop_cvterm_lookup[strtolower($cvterm->name)] = $cvterm->cvterm_id;
  572. $this->featureprop_cvterm_lookup[strtolower($type)] = $cvterm->cvterm_id;
  573. }
  574. else {
  575. $this->feature_cvterm_lookup[strtolower($cvterm->name)] = $cvterm->cvterm_id;
  576. $this->feature_cvterm_lookup[strtolower($type)] = $cvterm->cvterm_id;
  577. // If the cvterm name does not match the name provided then set a mapping.
  578. if ($cvterm->name != $type) {
  579. $this->feature_cvterm_aliases[$type] = $cvterm->name;
  580. }
  581. }
  582. return $cvterm->cvterm_id;
  583. }
  584. /**
  585. * Makes sure Chado is ready with the necessary synonym type records.
  586. */
  587. private function prepSynonms() {
  588. // make sure we have a 'synonym_type' vocabulary
  589. $select = ['name' => 'synonym_type'];
  590. $results = chado_select_record('cv', ['*'], $select);
  591. if (count($results) == 0) {
  592. // insert the 'synonym_type' vocabulary
  593. $values = [
  594. 'name' => 'synonym_type',
  595. 'definition' => 'vocabulary for synonym types',
  596. ];
  597. $success = chado_insert_record('cv', $values, array(
  598. 'skip_validation' => TRUE,
  599. ));
  600. if (!$success) {
  601. $this->logMessage("Failed to add the synonyms type vocabulary.", [], TRIPAL_WARNING);
  602. return 0;
  603. }
  604. // now that we've added the cv we need to get the record
  605. $results = chado_select_record('cv', ['*'], $select);
  606. if (count($results) > 0) {
  607. $syncv = $results[0];
  608. }
  609. }
  610. else {
  611. $syncv = $results[0];
  612. }
  613. // get the 'exact' cvterm, which is the type of synonym we're adding
  614. $select = [
  615. 'name' => 'exact',
  616. 'cv_id' => [
  617. 'name' => 'synonym_type',
  618. ],
  619. ];
  620. $result = chado_select_record('cvterm', ['*'], $select);
  621. if (count($result) == 0) {
  622. $term = [
  623. 'name' => 'exact',
  624. 'id' => "synonym_type:exact",
  625. 'definition' => '',
  626. 'is_obsolete' => 0,
  627. 'cv_name' => $syncv->name,
  628. 'is_relationship' => FALSE,
  629. ];
  630. $syntype = chado_insert_cvterm($term, ['update_existing' => TRUE]);
  631. if (!$syntype) {
  632. $this->logMessage("Cannot add synonym type: internal:$type.", [], TRIPAL_WARNING);
  633. return 0;
  634. }
  635. }
  636. else {
  637. $syntype = $result[0];
  638. }
  639. $this->exact_syn = $syntype;
  640. }
  641. /**
  642. * Makes sure there is a null publication in the database.
  643. */
  644. private function prepNullPub(){
  645. // Check to see if we have a NULL publication in the pub table. If not,
  646. // then add one.
  647. $select = ['uniquename' => 'null'];
  648. $result = chado_select_record('pub', ['*'], $select);
  649. if (count($result) == 0) {
  650. $pub_sql = "
  651. INSERT INTO {pub} (uniquename,type_id)
  652. VALUES (:uname,
  653. (SELECT cvterm_id
  654. FROM {cvterm} CVT
  655. INNER JOIN {dbxref} DBX ON DBX.dbxref_id = CVT.dbxref_id
  656. INNER JOIN {db} DB ON DB.db_id = DBX.db_id
  657. WHERE CVT.name = :type_id))
  658. ";
  659. $status = chado_query($psql);
  660. if (!$status) {
  661. $this->logMessage("Cannot prepare statement 'ins_pub_uniquename_typeid.", [], TRIPAL_WARNING);
  662. return 0;
  663. }
  664. // Insert the null pub.
  665. $result = chado_query($pub_sql, [
  666. ':uname' => 'null',
  667. ':type_id' => 'null',
  668. ])->fetchObject();
  669. if (!$result) {
  670. $this->logMessage("Cannot add null publication needed for setup of alias.", [], TRIPAL_WARNING);
  671. return 0;
  672. }
  673. $result = chado_select_record('pub', ['*'], $select);
  674. $pub = $result[0];
  675. }
  676. else {
  677. $pub = $result[0];
  678. }
  679. $this->null_pub = $pub;
  680. }
  681. /**
  682. * Makes sure Chado is ready with the necessary DB records.
  683. */
  684. private function prepDBs() {
  685. // Get the list of database records that are needed by this GFF file. If
  686. // they do not exist then add them.
  687. $sql = "
  688. SELECT db_id
  689. FROM {db}
  690. WHERE name = :dbname";
  691. foreach (array_keys($this->db_lookup) as $dbname) {
  692. // First look for the database name if it doesn't exist then create one.
  693. // first check for the fully qualified URI (e.g. DB:<dbname>. If that
  694. // can't be found then look for the name as is. If it still can't be found
  695. // the create the database
  696. $values = ['name' => "DB:$dbname"];
  697. $db = chado_select_record('db', ['db_id'], $values);
  698. if (count($db) == 0) {
  699. $values = ['name' => "$dbname"];
  700. $db = chado_select_record('db', ['db_id'], $values);
  701. }
  702. if (count($db) == 0) {
  703. $values = [
  704. 'name' => $dbname,
  705. 'description' => 'Added automatically by the Triapl GFF loader.',
  706. ];
  707. $success = chado_insert_record('db', $values, array(
  708. 'skip_validation' => TRUE,
  709. ));
  710. if ($success) {
  711. $values = ['name' => "$dbname"];
  712. $db = chado_select_record('db', ['db_id'], $values);
  713. }
  714. else {
  715. $this->logMessage("Cannot find or add the database $dbname.", [], TRIPAL_WARNING);
  716. return 0;
  717. }
  718. }
  719. $this->db_lookup[$dbname] = $db[0]->db_id;
  720. }
  721. }
  722. /**
  723. * Parses the current line of the GFF3 file for a feature.
  724. *
  725. * @return array
  726. * An associative array containing the 9 elements othe GFF3 file. The
  727. * 9th element is an associative array of the attributes.
  728. */
  729. private function parseFeature($line) {
  730. $date = getdate();
  731. // get the columns
  732. $cols = explode("\t", $line);
  733. if (sizeof($cols) != 9) {
  734. throw new Exception(t('Improper number of columns on line %line_num: %line', ['%line_num' => $this->current_line, '%line' => $line]));
  735. }
  736. $ret = [
  737. 'line' => $this->current_line,
  738. 'landmark' => $cols[0],
  739. 'source' => $cols[1],
  740. 'type' => $cols[2],
  741. 'start' => $cols[3],
  742. 'end' => $cols[4],
  743. 'score' => $cols[5],
  744. 'strand' => $cols[6],
  745. 'phase' => $cols[7],
  746. 'attrs' => [],
  747. ];
  748. // Ready the start and stop for chado. Chado expects these positions
  749. // to be zero-based, so we substract 1 from the fmin. Also, in case
  750. // they are backwards, put them in the right order.
  751. $fmin = $ret['start'] - 1;
  752. $fmax = $ret['end'];
  753. if ($ret['end'] < $ret['start']) {
  754. $fmin = $ret['end'] - 1;
  755. $fmax = $ret['start'];
  756. }
  757. $ret['start'] = $fmin;
  758. $ret['stop'] = $fmax;
  759. // Format the strand for chado
  760. if (strcmp($ret['strand'], '.') == 0) {
  761. $ret['strand'] = 0;
  762. }
  763. elseif (strcmp($ret['strand'], '+') == 0) {
  764. $ret['strand'] = 1;
  765. }
  766. elseif (strcmp($ret['strand'], '-') == 0) {
  767. $ret['strand'] = -1;
  768. }
  769. if (strcmp($ret['phase'], '.') == 0) {
  770. if (strtolower($ret['type']) == 'cds') {
  771. $ret['phase'] = '0';
  772. }
  773. else {
  774. $ret['phase'] = '';
  775. }
  776. }
  777. $tags = [];
  778. $attr_name = '';
  779. $attr_uniquename = '';
  780. $attrs = explode(";", $cols[8]);
  781. $attr_organism = [];
  782. $attr_parent = '';
  783. $attr_others = [];
  784. $attr_aliases = [];
  785. $attr_dbxref = [];
  786. $attr_derives = [];
  787. $attr_terms = [];
  788. foreach ($attrs as $attr) {
  789. $attr = rtrim($attr);
  790. $attr = ltrim($attr);
  791. if (strcmp($attr, '') == 0) {
  792. continue;
  793. }
  794. if (!preg_match('/^[^\=]+\=.+$/', $attr)) {
  795. throw new Exception(t('Attribute is not correctly formatted on line %line_num: %attr',
  796. ['%line_num' => $this->current_line, '%attr' => $attr]));
  797. }
  798. // Break apart each attribute into key/value pairs.
  799. $tag = preg_split("/=/", $attr, 2);
  800. // Multiple values of an attribute are separated by commas
  801. $tag_name = $tag[0];
  802. if (!array_key_exists($tag_name, $tags)) {
  803. $tags[$tag_name] = [];
  804. }
  805. $tags[$tag_name] = array_merge($tags[$tag_name], explode(",", $tag[1]));
  806. // Replace the URL escape codes for each tag
  807. for ($i = 0; $i < count($tags[$tag_name]); $i++) {
  808. $tags[$tag_name][$i] = urldecode($tags[$tag_name][$i]);
  809. }
  810. if (strcmp($tag_name, 'Alias') == 0) {
  811. $attr_aliases = array_merge($attr_aliases, $tags[$tag_name]);
  812. }
  813. elseif (strcmp($tag_name, 'Parent') == 0) {
  814. $attr_parent = urldecode($tag[1]);
  815. }
  816. elseif (strcmp($tag_name, 'Dbxref') == 0) {
  817. $attr_dbxref = array_merge($attr_dbxref, $tags[$tag_name]);
  818. }
  819. elseif (strcmp($tag_name, 'Derives_from') == 0) {
  820. $attr_derives = array_merge($attr_derives, $tags[$tag_name]);
  821. }
  822. elseif (strcmp($tag_name, 'Ontology_term') == 0) {
  823. $attr_terms = array_merge($attr_terms, $tags[$tag_name]);
  824. }
  825. elseif (strcmp($tag_name, 'organism') == 0) {
  826. $attr_organism = array_merge($attr_organism, $tags[$tag_name]);
  827. }
  828. // Get the list of non-reserved attributes these will get added
  829. // as properties to the featureprop table. The 'Note' and 'Gap'
  830. // attributes will go in as a property so those are not in the list
  831. // checked below.
  832. elseif (strcmp($tag_name, 'Name') !=0 and strcmp($tag_name, 'ID') !=0 and
  833. strcmp($tag_name, 'Alias') != 0 and strcmp($tag_name, 'Parent') != 0 and
  834. strcmp($tag_name, 'Target') != 0 and strcmp($tag_name, 'Derives_from') != 0 and
  835. strcmp($tag_name, 'Dbxref') != 0 and strcmp($tag_name, 'Ontology_term') != 0 and
  836. strcmp($tag_name, 'Is_circular') != 0 and strcmp($tag_name, 'target_organism') != 0 and
  837. strcmp($tag_name, 'target_type') != 0 and strcmp($tag_name, 'organism' != 0)) {
  838. foreach ($tags[$tag_name] as $value) {
  839. if (!array_key_exists($tag_name, $attr_others)) {
  840. $attr_others[$tag_name] = [];
  841. }
  842. $attr_others[$tag_name][] = $value;
  843. }
  844. }
  845. }
  846. // If neither name nor uniquename are provided then generate one.
  847. $names = $this->getFeatureName($tags, $ret['type'], $ret['landmark'], $fmin, $fmax);
  848. $attr_uniquename = $names['uniquename'];
  849. $attr_name = $names['name'];
  850. $ret['name'] = $attr_name;
  851. $ret['uniquename'] = $attr_uniquename;
  852. $ret['synonyms'] = $attr_aliases;
  853. // Add in the dbxref record.
  854. $ret['dbxrefs'] = [];
  855. foreach ($attr_dbxref as $key => $dbx) {
  856. $parts = explode(':', $dbx, 2);
  857. $ret['dbxrefs']["{$parts[0]}:{$parts[1]}"] = array(
  858. 'db' => $parts[0],
  859. 'accession' => $parts[1],
  860. );
  861. }
  862. // Add in the GFF source dbxref. This is needed for GBrowse.
  863. $ret['dbxrefs']["GFF_source:{$ret['source']}"] = array(
  864. 'db' => 'GFF_source',
  865. 'accession' => $ret['source'],
  866. );
  867. // Add in the ontology terms
  868. $ret['terms'] = [];
  869. foreach ($attr_terms as $key => $dbx) {
  870. $parts = explode(':', $dbx, 2);
  871. $ret['terms']["{$parts[0]}:{$parts[1]}"] = array(
  872. 'db' => $parts[0],
  873. 'accession' => $parts[1],
  874. );
  875. }
  876. // Add the derives from entry.
  877. $ret['derives_from'] = '';
  878. if (count($attr_derives) == 1) {
  879. $ret['derives_from'] = $attr_derives[0];
  880. }
  881. if (count($attr_derives) > 1) {
  882. throw new Exception(t('Each feature can only have one "Derives_from" attribute. The feature %uniquename has more than one: %derives',
  883. [
  884. '%uniquename' => $ret['uniquename'],
  885. '%derives' => $ret['derives_from'],
  886. ]));
  887. }
  888. // Now add all of the attributes into the return array.
  889. foreach ($tags as $key => $value) {
  890. $ret['attrs'][$key] = $value;
  891. }
  892. // Add the organism entry.
  893. $ret['organism'] = '';
  894. if (count($attr_organism) == 1) {
  895. $ret['organism'] = $attr_organism[0];
  896. }
  897. if (count($attr_organism) > 1) {
  898. throw new Exception(t('Each feature can only have one "organism" attribute. The feature %uniquename has more than one: %organism',
  899. [
  900. '%uniquename' => $ret['uniquename'],
  901. '%organism' => $ret['organism'],
  902. ]));
  903. }
  904. $ret['properties'] = $attr_others;
  905. $ret['parent'] = $attr_parent;
  906. return $ret;
  907. }
  908. /**
  909. * Indexes the FASTA section of the file for quick lookup.
  910. */
  911. private function indexFASTA() {
  912. // Iterate through the remaining lines of the file
  913. while ($line = fgets($this->gff_file_h)) {
  914. $this->current_line++;
  915. $this->addItemsHandled(drupal_strlen($line));
  916. // Get the ID and the current file pointer and store that for later.
  917. if (preg_match('/^>/', $line)) {
  918. $id = preg_replace('/^>([^\s]+).*$/', '\1', $line);
  919. $this->residue_index[trim($id)] = ftell($this->gff_file_h);
  920. }
  921. }
  922. }
  923. /**
  924. * Loads the actual residue information from the FASTA section of the file.
  925. */
  926. private function insertFeatureSeqs() {
  927. $num_residues = count(array_keys($this->residue_index));
  928. $this->setItemsHandled(0);
  929. $this->setTotalItems($num_residues);
  930. $count = 0;
  931. foreach ($this->residue_index as $uniquename => $offset) {
  932. $is_landmark = FALSE;
  933. if (!(array_key_exists($uniquename, $this->features) and $this->features[$uniquename]) and !(array_key_exists($uniquename, $this->landmarks) and $this->landmarks[$uniquename])) {
  934. $this->logMessage('Cannot find feature to assign FASTA sequence: %uname.',
  935. ['%uname' => $uniquename], TRIPAL_WARNING);
  936. $count++;
  937. continue;
  938. }
  939. if (array_key_exists($uniquename, $this->features)) {
  940. $feature = $this->features[$uniquename];
  941. }
  942. else {
  943. $feature = $this->landmarks[$uniquename];
  944. $is_landmark = TRUE;
  945. }
  946. $this->ensureFeatureIsLoaded($feature);
  947. $id = $feature['feature_id'];
  948. $residues = [];
  949. fseek($this->gff_file_h, $offset);
  950. while ($line = fgets($this->gff_file_h)) {
  951. if (preg_match('/^>/', $line)) {
  952. break;
  953. }
  954. $residues[] = trim($line);
  955. }
  956. $residues = implode('', $residues);
  957. $feature['residues'] = $residues;
  958. if (!$is_landmark) {
  959. $this->features[$uniquename] = $feature;
  960. }
  961. else {
  962. $this->landmarks[$uniquename] = $feature;
  963. }
  964. chado_update_record('feature', ['feature_id' => $id], [
  965. 'residues' => $residues,
  966. 'seqlen' => strlen($residues),
  967. 'md5checksum' => md5($residues),
  968. ]);
  969. $count++;
  970. $this->setItemsHandled($count);
  971. }
  972. }
  973. /**
  974. * Retrieves a ChadoRecord object for the landmark feature.
  975. *
  976. * @param $landmark_name
  977. * The name of the landmark to get
  978. *
  979. * @return
  980. * A feature ChadoRecord object or NULL if the landmark is missing and
  981. * $skip_on_missing is TRUE.
  982. */
  983. private function findLandmark($landmark_name) {
  984. // Before performing a database query check to see if
  985. // this landmark is already in our lookup list.
  986. if (array_key_exists($landmark_name, $this->landmarks)) {
  987. return $this->landmarks[$landmark_name];
  988. }
  989. $landmark = new ChadoRecord('feature');
  990. $landmark->setValues([
  991. 'organism_id' => $this->organism_id,
  992. 'uniquename' => $landmark_name,
  993. ]);
  994. if ($landmark_type) {
  995. $landmark->setValue('type_id', $landmark_type->getValue('cvterm_id'));
  996. }
  997. $num_found = $landmark->find();
  998. if ($num_found == 0) {
  999. return NULL;
  1000. }
  1001. if ($num_found > 1) {
  1002. throw new Exception(t("The landmark '%landmark' has more than one entry for this organism (%species). Did you provide a landmark type? If not, try resubmitting and providing a type." .
  1003. "Cannot continue", [
  1004. '%landmark' => $landmark_name,
  1005. '%species' => $this->organism->getValues('genus') . " " . $this->organism->getValues('species'),
  1006. ]));
  1007. }
  1008. // The landmark was found, remember it
  1009. $this->landmarks[$landmark_name] = $landmark;
  1010. return $landmark;
  1011. }
  1012. /**
  1013. * Loads into the database any landmark sequences.
  1014. *
  1015. * @param $line
  1016. * The line from the GFF file that is the ##sequence-region comment.
  1017. */
  1018. private function insertHeaderLandmark($line) {
  1019. $region_matches = [];
  1020. if (preg_match('/^##sequence-region\s+(\w*?)\s+(\d+)\s+(\d+)$/i', $line, $region_matches)) {
  1021. $rid = $region_matches[1];
  1022. $landmark = $this->findLandmark($rid);
  1023. if (!$landmark) {
  1024. $rstart = $region_matches[2];
  1025. $rend = $region_matches[3];
  1026. if (!$this->landmark_type) {
  1027. throw new Exception(t('The landmark, !landmark, cannot be added becuase no landmark type was provided. Please redo the importer job and specify a landmark type.',
  1028. ['!landmark' => $rid]));
  1029. }
  1030. $this->insertLandmark($rid);
  1031. }
  1032. }
  1033. }
  1034. /**
  1035. * Loads a single landmark by name.
  1036. */
  1037. private function insertLandmark($name) {
  1038. //$this->logMessage('Adding a new landmark feature: !landmark', ['!landmark' => $name]);
  1039. $landmark = $this->insertFeature($this->organism, $this->analysis, $this->landmark_cvterm, $name,
  1040. $name, '', 'f', 'f', 1, 0);
  1041. $this->landmarks[$name] = [
  1042. 'uniquename' => $landmark->getValue('uniquename'),
  1043. 'name' => $landmark->getValue('name'),
  1044. 'type' => $this->landmark_cvterm->getValue('name'),
  1045. 'feature_id' => $landmark->getValue('feature_id'),
  1046. 'organism_id' => $landmark->getValue('organism_id'),
  1047. ];
  1048. }
  1049. /**
  1050. *
  1051. */
  1052. private function parseGFF3() {
  1053. $filesize = filesize($this->gff_file);
  1054. $this->setTotalItems($filesize);
  1055. // Holds a unique list of cvterms for later lookup.
  1056. $feature_cvterms = [];
  1057. $featureprop_cvterms = [];
  1058. while ($line = fgets($this->gff_file_h)) {
  1059. $this->current_line++;
  1060. $this->addItemsHandled(drupal_strlen($line));
  1061. $line = trim($line);
  1062. if ($this->current_line < $this->start_line) {
  1063. continue;
  1064. }
  1065. // If we're in the FASTA file we're at the end of the features so return.
  1066. if (preg_match('/^##FASTA/i', $line)) {
  1067. $this->indexFASTA();
  1068. continue;
  1069. }
  1070. // if at the ##sequence-region line handle it.
  1071. $matches = [];
  1072. if (preg_match('/^##sequence-region\s+(\w*?)\s+(\d+)\s+(\d+)$/i', $line, $matches)) {
  1073. $this->seq_region_headers[$matches[1]] = $line;
  1074. continue;
  1075. }
  1076. // skip comments
  1077. if (preg_match('/^#/', $line)) {
  1078. continue;
  1079. }
  1080. // skip empty lines
  1081. if (preg_match('/^\s*$/', $line)) {
  1082. continue;
  1083. }
  1084. // Parse this feature from this line of the GFF3 file.
  1085. $gff_feature = $this->parseFeature($line);
  1086. $gff_feature['feature_id'] = NULL;
  1087. // A feature may get ignored. But let's default this to FALSE.
  1088. $gff_feature['skipped'] = FALSE;
  1089. // Lookup the organism ID if one is requested.
  1090. if ($gff_feature['organism']) {
  1091. $organism_id = $this->findOrganism($gff_feature['organism'], $line_num);
  1092. if ($organism_id) {
  1093. $gff_feature['organism'] = $organism_id;
  1094. }
  1095. elsE {
  1096. $gff_feature['skipped'] = TRUE;
  1097. }
  1098. }
  1099. // Add the landmark if it doesn't exist in the landmark list.
  1100. if (!array_key_exists($gff_feature['landmark'], $this->landmarks)) {
  1101. $this->landmarks[$gff_feature['landmark']] = FALSE;
  1102. }
  1103. // Organize DBs and DBXrefs for faster access later on.
  1104. foreach ($gff_feature['dbxrefs'] as $index => $info) {
  1105. if (!array_key_exists($info['db'], $this->db_lookup)) {
  1106. $this->db_lookup[$info['db']] = FALSE;
  1107. }
  1108. if (!array_key_exists($index, $this->dbxref_lookup)) {
  1109. $this->dbxref_lookup[$index] = $info;
  1110. }
  1111. }
  1112. // We want to make sure the Ontology_term attribute dbxrefs are
  1113. // also easily looked up... but we do not want to create them
  1114. // if they do not exist the precense of the 'cvterm' key will
  1115. // tell the loadDbxrefs() function to not create the term.
  1116. foreach ($gff_feature['terms'] as $index => $info) {
  1117. if (!array_key_exists($info['db'], $this->db_lookup)) {
  1118. $this->db_lookup[$info['db']] = FALSE;
  1119. }
  1120. if (!array_key_exists($index, $this->dbxref_lookup)) {
  1121. $this->dbxref_lookup[$index] = $info;
  1122. $this->dbxref_lookup[$index]['cvterm_id'] = NULL;
  1123. }
  1124. }
  1125. // Organize the CVterms for faster access later on.
  1126. if (!array_key_exists($gff_feature['type'], $feature_cvterms)) {
  1127. $feature_cvterms[$gff_feature['type']] = 0;
  1128. }
  1129. $feature_cvterms[$gff_feature['type']]++;
  1130. // Organize the feature property types for faster access later on.
  1131. foreach ($gff_feature['properties'] as $prop_name => $value) {
  1132. if (!array_key_exists($prop_name, $featureprop_cvterms)) {
  1133. $featureprop_cvterms[$prop_name] = 0;
  1134. }
  1135. $featureprop_cvterms[$prop_name]++;
  1136. }
  1137. // Store the GFF feature details.
  1138. if ($gff_feature['uniquename'] != $gff_feature['landmark']) {
  1139. $this->features[$gff_feature['uniquename']] = $gff_feature;
  1140. }
  1141. }
  1142. // Iterate through the feature type terms and get a chado object for each.
  1143. $feature_cvterm_ids = [];
  1144. foreach ($feature_cvterms as $name => $counts) {
  1145. $cvterm_id = $this->getCvtermID($name, $this->feature_cv->getValue('cv_id'), FALSE);
  1146. $feature_cvterm_ids[] = $cvterm_id;
  1147. }
  1148. // Iterate through the featureprop type terms and get a cvterm_id for
  1149. // each. If it doesn't exist then add a new record.
  1150. foreach ($featureprop_cvterms as $name => $counts) {
  1151. $cvterm_id = $this->getCvtermID($name, $this->feature_prop_cv->getValue('cv_id'), TRUE);
  1152. if (!$cvterm_id) {
  1153. $term = [
  1154. 'id' => "local:$name",
  1155. 'name' => $name,
  1156. 'is_obsolete' => 0,
  1157. 'cv_name' => $this->feature_prop_cv->getValue('name'),
  1158. 'db_name' => 'local',
  1159. 'is_relationship' => FALSE,
  1160. ];
  1161. $cvterm = (object) chado_insert_cvterm($term, ['update_existing' => FALSE]);
  1162. if (!$cvterm) {
  1163. $this->logMessage("Cannot add cvterm, $name.", [], TRIPAL_WARNING);
  1164. return 0;
  1165. }
  1166. $this->featureprop_cvterm_lookup[strtolower($cvterm->name)] = $cvterm->cvterm_id;
  1167. }
  1168. }
  1169. }
  1170. /**
  1171. * Imports the landmark features into Chado.
  1172. */
  1173. private function insertLandmarks() {
  1174. foreach ($this->landmarks as $uniquename => $feature) {
  1175. // If the landmark does not have an entry in the GFF lines, try to
  1176. // find or add it.
  1177. if ($feature === FALSE) {
  1178. // First see if there is a definition in the headers region.
  1179. if (array_key_exists($uniquename, $this->seq_region_headers)) {
  1180. $this->insertHeaderLandmark($this->seq_region_headers[$uniquename]);
  1181. continue;
  1182. }
  1183. // Second, if a landmark_type is provided then just add the landmark feature.
  1184. else if ($this->landmark_type) {
  1185. $landmark = $this->findLandmark($uniquename);
  1186. if (!$landmark) {
  1187. $this->insertLandmark($uniquename);
  1188. }
  1189. }
  1190. else {
  1191. throw new Exception(t('The landmark (reference) sequence, !landmark, is not in the database and not specified in the GFF3 file. Please either pre-load the landmark sequences or set a "Landmark Type" in the GFF importer.',
  1192. ['!landmark' => $uniquename]));
  1193. }
  1194. }
  1195. }
  1196. }
  1197. /**
  1198. * Imports the feature records into Chado.
  1199. */
  1200. private function insertFeatures() {
  1201. $batch_size = 1000;
  1202. $num_features = count(array_keys($this->features));
  1203. $num_batches = (int) ($num_features / $batch_size) + 1;
  1204. $this->setItemsHandled(0);
  1205. $this->setTotalItems($num_batches);
  1206. $init_sql = "
  1207. INSERT INTO {feature}
  1208. (uniquename, name, type_id, organism_id, residues, md5checksum,
  1209. seqlen, is_analysis, is_obsolete)
  1210. VALUES\n";
  1211. $i = 0;
  1212. $total = 0;
  1213. $batch_num = 1;
  1214. $sql = '';
  1215. $args = [];
  1216. foreach ($this->features as $feature) {
  1217. $total++;
  1218. // Only do an insert if this feature doesn't already exist in the databse.
  1219. if (!$feature['feature_id'] and !$feature['skipped']) {
  1220. $i++;
  1221. $residues = $this->getResidues($feature, FALSE);
  1222. $type_id = $this->feature_cvterm_lookup[strtolower($feature['type'])];
  1223. $sql .= "(:uniquename_$i, :name_$i, :type_id_$i, :organism_id_$i, :residues_$i, " .
  1224. " :md5checksum_$i, :seqlen_$i, FALSE, FALSE),\n";
  1225. $args[":uniquename_$i"] = $feature['uniquename'];
  1226. $args[":name_$i"] = $feature['name'];
  1227. $args[":type_id_$i"] = $type_id;
  1228. $args[":organism_id_$i"] = $feature['organism'] ? $feature['organism'] : $this->organism->getID();
  1229. $args[":residues_$i"] = $residues;
  1230. $args[":md5checksum_$i"] = $residues ? md5($residues) : '';
  1231. $args[":seqlen_$i"] = strlen($residues);
  1232. }
  1233. // If we've reached the size of the batch then let's do the insert.
  1234. if ($i == $batch_size or $total == $num_features) {
  1235. if (count($args) > 0) {
  1236. $sql = rtrim($sql, ",\n");
  1237. $sql = $init_sql . $sql;
  1238. chado_query($sql, $args);
  1239. }
  1240. $this->setItemsHandled($batch_num);
  1241. $batch_num++;
  1242. // Now reset all of the varables for the next batch.
  1243. $sql = '';
  1244. $i = 0;
  1245. $args = [];
  1246. }
  1247. }
  1248. }
  1249. /**
  1250. * Check if the features exist in the database.
  1251. */
  1252. private function findFeatures() {
  1253. $batch_size = 1000;
  1254. $num_features = count(array_keys($this->features));
  1255. $num_batches = (int) ($num_features / $batch_size) + 1;
  1256. $this->setItemsHandled(0);
  1257. $this->setTotalItems($num_batches);
  1258. $sql = "SELECT uniquename, type_id, organism_id, feature_id FROM {feature} WHERE uniquename in (:uniquenames)";
  1259. $i = 0;
  1260. $total = 0;
  1261. $batch_num = 1;
  1262. $names = [];
  1263. foreach ($this->features as $uniquename => $feature) {
  1264. $total++;
  1265. if (!$feature['feature_id']) {
  1266. $i++;
  1267. $names[] = $uniquename;
  1268. }
  1269. // If we've reached the size of the batch then let's do the select.
  1270. if ($i == $batch_size or $total == $num_features) {
  1271. if (count($names) > 0) {
  1272. $args = [':uniquenames' => $names];
  1273. $results = chado_query($sql, $args);
  1274. while ($f = $results->fetchObject()) {
  1275. $matched_feature = $this->features[$f->uniquename];
  1276. $matched_type_id = $this->feature_cvterm_lookup[strtolower($matched_feature['type'])];
  1277. $matched_organism_id = $matched_feature['organism'] ? $matched_feature['organism'] : $this->organism->getID();
  1278. if ($matched_type_id == $f->type_id and $matched_organism_id == $f->organism_id) {
  1279. $this->features[$f->uniquename]['feature_id'] = $f->feature_id;
  1280. }
  1281. }
  1282. }
  1283. $this->setItemsHandled($batch_num);
  1284. $batch_num++;
  1285. // Now reset all of the varables for the next batch.
  1286. $i = 0;
  1287. $names = [];
  1288. }
  1289. }
  1290. }
  1291. /**
  1292. * Deletes all anciallary data about a feature so we can re-insert it.
  1293. */
  1294. private function deleteFeatureData() {
  1295. $batch_size = 1000;
  1296. $num_features = count(array_keys($this->features));
  1297. $num_batches = (int) ($num_features / $batch_size) + 1;
  1298. $this->setItemsHandled(0);
  1299. $this->setTotalItems($num_batches);
  1300. $sql1 = "DELETE from {featureprop} WHERE feature_id IN (:feature_ids)";
  1301. $sql2 = "DELETE from {featureloc} WHERE feature_id IN (:feature_ids)";
  1302. $sql3 = "DELETE from {feature_cvterm} WHERE feature_id IN (:feature_ids)";
  1303. $sql4 = "DELETE from {feature_dbxref} WHERE feature_id IN (:feature_ids)";
  1304. $sql5 = "DELETE from {feature_synonym} WHERE feature_id IN (:feature_ids)";
  1305. $sql6 = "DELETE from {feature_relationship} WHERE subject_id IN (:feature_ids)";
  1306. $i = 0;
  1307. $total = 0;
  1308. $batch_num = 1;
  1309. $feature_ids = [];
  1310. foreach ($this->features as $feature) {
  1311. $total++;
  1312. if ($feature['feature_id'] and !$feature['skipped']) {
  1313. $i++;
  1314. $feature_ids[] = $feature['feature_id'];
  1315. }
  1316. // If we've reached the size of the batch then let's do the insert.
  1317. if ($i == $batch_size or $total == $num_features) {
  1318. if (count($feature_ids) > 0) {
  1319. $args[':feature_ids'] = $feature_ids;
  1320. chado_query($sql1, $args);
  1321. chado_query($sql2, $args);
  1322. chado_query($sql3, $args);
  1323. chado_query($sql4, $args);
  1324. chado_query($sql5, $args);
  1325. chado_query($sql6, $args);
  1326. }
  1327. $this->setItemsHandled($batch_num);
  1328. $batch_num++;
  1329. // Now reset all of the varables for the next batch.
  1330. $i = 0;
  1331. $feature_ids = [];
  1332. }
  1333. }
  1334. }
  1335. /**
  1336. *
  1337. */
  1338. private function insertFeatureProps(){
  1339. $batch_size = 100;
  1340. $num_features = count(array_keys($this->features));
  1341. $num_batches = (int) ($num_features / $batch_size) + 1;
  1342. $this->setItemsHandled(0);
  1343. $this->setTotalItems($num_batches);
  1344. $init_sql = "INSERT INTO {featureprop} (feature_id, type_id, value, rank) VALUES\n";
  1345. $i = 0;
  1346. $j = 0;
  1347. $total = 0;
  1348. $batch_num = 1;
  1349. $sql = '';
  1350. $args = [];
  1351. foreach ($this->features as $feature) {
  1352. $total++;
  1353. // If the feature is not skipped
  1354. if (!$feature['skipped']) {
  1355. $i++;
  1356. // Iterate through all of the properties of this feature.
  1357. foreach ($feature['properties'] as $prop_name => $values) {
  1358. foreach ($values as $rank => $value) {
  1359. $j++;
  1360. $type_id = $this->featureprop_cvterm_lookup[strtolower($prop_name)];
  1361. $sql .= "(:feature_id_$j, :type_id_$j, :value_$j, :rank_$j),\n";
  1362. $args[":feature_id_$j"] = $feature['feature_id'];
  1363. $args[":type_id_$j"] = $type_id;
  1364. $args[":value_$j"] = $value;
  1365. $args[":rank_$j"] = $rank;
  1366. }
  1367. }
  1368. }
  1369. // If we've reached the size of the batch then let's do the insert.
  1370. if ($i == $batch_size or $total == $num_features) {
  1371. if (count($args) > 0) {
  1372. $sql = rtrim($sql, ",\n");
  1373. $sql = $init_sql . $sql;
  1374. chado_query($sql, $args);
  1375. }
  1376. $this->setItemsHandled($batch_num);
  1377. $batch_num++;
  1378. // Now reset all of the varables for the next batch.
  1379. $sql = '';
  1380. $i = 0;
  1381. $j = 0;
  1382. $args = [];
  1383. }
  1384. }
  1385. }
  1386. /**
  1387. *
  1388. */
  1389. private function insertFeatureParents(){
  1390. $batch_size = 100;
  1391. $num_parents = count(array_keys($this->parent_lookup));
  1392. $num_batches = (int) ($num_parents / $batch_size) + 1;
  1393. $this->setItemsHandled(0);
  1394. $this->setTotalItems($num_batches);
  1395. // Get the 'part_of' cvterm
  1396. $type_id = $this->getCvtermID('part_of');
  1397. $init_sql = "INSERT INTO {feature_relationship} (subject_id, object_id, type_id, rank) VALUES\n";
  1398. $i = 0;
  1399. $j = 0;
  1400. $total = 0;
  1401. $batch_num = 1;
  1402. $sql = '';
  1403. $args = [];
  1404. foreach ($this->parent_lookup as $parent => $children) {
  1405. $total++;
  1406. $parent_feature = $this->features[$parent];
  1407. if (!$parent_feature['skipped']) {
  1408. $i++;
  1409. $rank = 0;
  1410. foreach ($children as $feature_id) {
  1411. $j++;
  1412. $sql .= "(:subject_id_$j, :object_id_$j, :type_id_$j, :rank_$j),\n";
  1413. $args[":subject_id_$j"] = $feature_id;
  1414. $args[":object_id_$j"] = $this->features[$parent]['feature_id'];
  1415. $args[":type_id_$j"] = $type_id;
  1416. $args[":rank_$j"] = $rank;
  1417. $rank++;
  1418. }
  1419. }
  1420. // If we've reached the size of the batch then let's do the insert.
  1421. if ($i == $batch_size or $total == $num_parents) {
  1422. if (count($args) > 0) {
  1423. $sql = rtrim($sql, ",\n");
  1424. $sql = $init_sql . $sql;
  1425. chado_query($sql, $args);
  1426. }
  1427. $this->setItemsHandled($batch_num);
  1428. $batch_num++;
  1429. // Now reset all of the varables for the next batch.
  1430. $sql = '';
  1431. $i = 0;
  1432. $j = 0;
  1433. $args = [];
  1434. }
  1435. }
  1436. }
  1437. /**
  1438. *
  1439. */
  1440. private function findDbxrefs() {
  1441. $batch_size = 1000;
  1442. $num_dbxrefs = count(array_keys($this->dbxref_lookup));
  1443. $num_batches = (int) ($num_dbxrefs / $batch_size) + 1;
  1444. $this->setItemsHandled(0);
  1445. $this->setTotalItems($num_batches);
  1446. // DBXrefs may be already present so we'll do an initial round of
  1447. // looking for them and then insert those that don't exist.
  1448. $init_sql = "
  1449. SELECT DB.name, DBX.db_id, DBX.accession, DBX.dbxref_id, CVT.cvterm_id
  1450. FROM {dbxref} DBX
  1451. INNER JOIN {db} DB on DB.db_id = DBX.db_id
  1452. LEFT JOIN {cvterm} CVT on DBX.dbxref_id = CVT.dbxref_id
  1453. WHERE
  1454. ";
  1455. $i = 0;
  1456. $total = 0;
  1457. $batch_num = 1;
  1458. $sql = '';
  1459. $args = [];
  1460. foreach ($this->dbxref_lookup as $xref => $info) {
  1461. $i++;
  1462. $total++;
  1463. $sql .= "(DBX.accession = :accession_$i and DBX.db_id = :db_id_$i) OR\n";
  1464. $args[":accession_$i"] = $info['accession'];
  1465. $args[":db_id_$i"] = $this->db_lookup[$info['db']];
  1466. // If we've reached the size of the batch then let's do the select.
  1467. if ($i == $batch_size or $total == $num_dbxrefs) {
  1468. $sql = rtrim($sql, " OR\n");
  1469. $sql = $init_sql . $sql;
  1470. $results = chado_query($sql, $args);
  1471. while ($dbxref = $results->fetchObject()) {
  1472. $index = $dbxref->name . ':' . $dbxref->accession;
  1473. $this->dbxref_lookup[$index]['dbxref_id'] = $dbxref->dbxref_id;
  1474. if ($dbxref->cvterm_id) {
  1475. $this->cvterm_lookup[$index] = $dbxref->cvterm_id;
  1476. $this->dbxref_lookup[$index]['cvterm_id'] = $dbxref->cvterm_id;
  1477. }
  1478. }
  1479. $this->setItemsHandled($batch_num);
  1480. $batch_num++;
  1481. // Now reset all of the varables for the next batch.
  1482. $sql = '';
  1483. $i = 0;
  1484. $j = 0;
  1485. $args = [];
  1486. }
  1487. }
  1488. }
  1489. /**
  1490. * Calculates ranks for all of the children of each feature.
  1491. *
  1492. * This function should not be executed until after features are loaded
  1493. * into the database and we have feature_ids for all of them.
  1494. */
  1495. private function findChildRanks() {
  1496. // Iterate through parent-child relationships and set the ranks.
  1497. foreach ($this->features as $uniquename => $feature) {
  1498. if ($feature['parent']) {
  1499. // place features in order that they appear by their start coordinates.
  1500. $parent = $feature['parent'];
  1501. $start = $feature['start'];
  1502. $this->parent_lookup[$parent][$start] = $feature['feature_id'];
  1503. }
  1504. }
  1505. }
  1506. /**
  1507. *
  1508. */
  1509. private function insertDbxrefs() {
  1510. $batch_size = 1000;
  1511. $num_dbxrefs = count(array_keys($this->dbxref_lookup));
  1512. $num_batches = (int) ($num_dbxrefs / $batch_size) + 1;
  1513. $this->setItemsHandled(0);
  1514. $this->setTotalItems($num_batches);
  1515. $init_sql = "INSERT INTO {dbxref} (db_id, accession) VALUES\n";
  1516. $i = 0;
  1517. $total = 0;
  1518. $batch_num = 1;
  1519. $sql = '';
  1520. $args = [];
  1521. foreach ($this->dbxref_lookup as $info) {
  1522. $i++;
  1523. $total++;
  1524. // Only do an insert if this dbxref doesn't already exist in the databse.
  1525. // and this dbxref is from a Dbxref attribute not an Ontology_term attr.
  1526. if (!array_key_exists('dbxref_id', $info) and
  1527. !array_key_exists('cvterm_id', $info)) {
  1528. $sql .= "(:db_id_$i, :accession_$i),\n";
  1529. $args[":db_id_$i"] = $this->db_lookup[$info['db']];
  1530. $args[":accession_$i"] = $info['accession'];
  1531. }
  1532. // If we've reached the size of the batch then let's do the insert.
  1533. if ($i == $batch_size or $total == $num_dbxrefs) {
  1534. if (count($args) > 0) {
  1535. $sql = rtrim($sql, ",\n");
  1536. $sql = $init_sql . $sql;
  1537. chado_query($sql, $args);
  1538. }
  1539. $this->setItemsHandled($batch_num);
  1540. $batch_num++;
  1541. // Now reset all of the varables for the next batch.
  1542. $sql = '';
  1543. $i = 0;
  1544. $j = 0;
  1545. $args = [];
  1546. }
  1547. }
  1548. }
  1549. /**
  1550. *
  1551. */
  1552. private function insertFeatureDbxrefs() {
  1553. $batch_size = 100;
  1554. $num_features = count(array_keys($this->features));
  1555. $num_batches = (int) ($num_features / $batch_size) + 1;
  1556. $this->setItemsHandled(0);
  1557. $this->setTotalItems($num_batches);
  1558. // Don't need to use placeholders for this insert since we are only using integers.
  1559. $init_sql = "INSERT INTO {feature_dbxref} (feature_id, dbxref_id) VALUES \n";
  1560. $i = 0;
  1561. $j = 0;
  1562. $total = 0;
  1563. $batch_num = 1;
  1564. $sql = '';
  1565. $args = [];
  1566. foreach ($this->features as $feature) {
  1567. $total++;
  1568. // If the feature is not skipped
  1569. if (!$feature['skipped']) {
  1570. $i++;
  1571. // Iterate through all of the dbxrefs of this feature.
  1572. foreach ($feature['dbxrefs'] as $index => $info) {
  1573. $j++;
  1574. $sql .= "(:feature_id_$j, :dbxref_id_$j),\n";
  1575. $args[":feature_id_$j"] = $feature['feature_id'];
  1576. $args[":dbxref_id_$j"] = $this->dbxref_lookup[$index]['dbxref_id'];
  1577. }
  1578. }
  1579. // If we've reached the size of the batch then let's do the insert.
  1580. if ($i == $batch_size or $total == $num_features) {
  1581. if (count($args) > 0) {
  1582. $sql = rtrim($sql, ",\n");
  1583. $sql = $init_sql . $sql;
  1584. chado_query($sql, $args);
  1585. }
  1586. $this->setItemsHandled($batch_num);
  1587. $batch_num++;
  1588. // Now reset all of the varables for the next batch.
  1589. $sql = '';
  1590. $i = 0;
  1591. $j = 0;
  1592. $args = [];
  1593. }
  1594. }
  1595. }
  1596. /**
  1597. *
  1598. */
  1599. private function insertFeatureCVterms() {
  1600. $batch_size = 100;
  1601. $num_features = count(array_keys($this->features));
  1602. $num_batches = (int) ($num_features / $batch_size) + 1;
  1603. $this->setItemsHandled(0);
  1604. $this->setTotalItems($num_batches);
  1605. // Don't need to use placeholders for this insert since we are only using integers.
  1606. $init_sql = "INSERT INTO {feature_cvterm} (feature_id, cvterm_id, pub_id) VALUES \n";
  1607. $i = 0;
  1608. $j = 0;
  1609. $total = 0;
  1610. $batch_num = 1;
  1611. $sql = '';
  1612. $args = [];
  1613. foreach ($this->features as $feature) {
  1614. $total++;
  1615. // If the feature is not skipped
  1616. if (!$feature['skipped']) {
  1617. $i++;
  1618. // Iterate through all of the dbxrefs of this feature.
  1619. foreach ($feature['terms'] as $index => $info) {
  1620. $j++;
  1621. $sql .= "(:feature_id_$j, :cvterm_id_$j, :pub_id_$j),\n";
  1622. $args[":feature_id_$j"] = $feature['feature_id'];
  1623. $args[":cvterm_id_$j"] = $this->cvterm_lookup[$index];
  1624. $args[":pub_id_$j"] = $this->null_pub->pub_id;
  1625. }
  1626. }
  1627. // If we've reached the size of the batch then let's do the insert.
  1628. if ($i == $batch_size or $total == $num_features) {
  1629. if (count($args) > 0) {
  1630. $sql = rtrim($sql, ",\n");
  1631. $sql = $init_sql . $sql;
  1632. chado_query($sql, $args);
  1633. }
  1634. $this->setItemsHandled($batch_num);
  1635. $batch_num++;
  1636. // Now reset all of the varables for the next batch.
  1637. $sql = '';
  1638. $i = 0;
  1639. $j = 0;
  1640. $args = [];
  1641. }
  1642. }
  1643. }
  1644. /**
  1645. *
  1646. */
  1647. private function insertFeatureDerivesFrom() {
  1648. $batch_size = 100;
  1649. $num_features = count(array_keys($this->features));
  1650. $num_batches = (int) ($num_features / $batch_size) + 1;
  1651. $this->setItemsHandled(0);
  1652. $this->setTotalItems($num_batches);
  1653. // Get the 'derives_from' cvterm
  1654. $type_id = $this->getCvtermID('derives_from');
  1655. $init_sql = "INSERT INTO {feature_relationship} (subject_id, object_id, type_id, rank) VALUES\n";
  1656. $i = 0;
  1657. $j = 0;
  1658. $total = 0;
  1659. $batch_num = 1;
  1660. $sql = '';
  1661. $args = [];
  1662. foreach ($this->features as $feature) {
  1663. $total++;
  1664. // If the feature is not skipped
  1665. if (!$feature['skipped'] and $feature['derives_from']) {
  1666. $i++;
  1667. $object_id = $this->features[$feature['derives_from']]['feature_id'];
  1668. $sql .= "(:subject_id_$i, :object_id_$i, :type_id_$i, 0),\n";
  1669. $args[":subject_id_$i"] = $feature['feature_id'];
  1670. $args[":object_id_$i"] = $object_id;
  1671. $args[":type_id_$i"] = $type_id;
  1672. }
  1673. // If we've reached the size of the batch then let's do the insert.
  1674. if ($i == $batch_size or $total == $num_features) {
  1675. if (count($args) > 0) {
  1676. $sql = rtrim($sql, ",\n");
  1677. $sql = $init_sql . $sql;
  1678. chado_query($sql, $args);
  1679. }
  1680. $this->setItemsHandled($batch_num);
  1681. $batch_num++;
  1682. // Now reset all of the varables for the next batch.
  1683. $sql = '';
  1684. $i = 0;
  1685. $j = 0;
  1686. $args = [];
  1687. }
  1688. }
  1689. }
  1690. /**
  1691. *
  1692. */
  1693. private function insertFeatureLocs() {
  1694. $batch_size = 1000;
  1695. $num_features = count(array_keys($this->features));
  1696. $num_batches = (int) ($num_features / $batch_size) + 1;
  1697. $this->setItemsHandled(0);
  1698. $this->setTotalItems($num_batches);
  1699. $init_sql = "
  1700. INSERT INTO {featureloc}
  1701. (srcfeature_id, feature_id, fmin, fmax, strand, phase, rank)
  1702. VALUES\n";
  1703. $i = 0;
  1704. $total = 0;
  1705. $batch_num = 1;
  1706. $sql = '';
  1707. $args = [];
  1708. foreach ($this->features as $feature) {
  1709. $total++;
  1710. // If the feature is not skipped
  1711. if (!$feature['skipped']) {
  1712. $i++;
  1713. // Get the rank of this feature by iterating through all siblings of the
  1714. // parent and finding where this feature is in terms of start position.
  1715. $rank = 0;
  1716. if (array_key_exists('Parent', $feature)) {
  1717. $children = $this->parent_lookup[$feature['parent']];
  1718. foreach ($children as $sib_start => $feature_id) {
  1719. if ($sib_start == $feature['start']) {
  1720. break;
  1721. }
  1722. $rank++;
  1723. }
  1724. }
  1725. $sql .= "(:srcfeature_id_$i, :feature_id_$i, :fmin_$i, :fmax_$i," .
  1726. " :strand_$i, :phase_$i, :rank_$i),\n";
  1727. $args[":srcfeature_id_$i"] = $this->landmarks[$feature['landmark']]['feature_id'];
  1728. $args[":feature_id_$i"] = $feature['feature_id'];
  1729. $args[":fmin_$i"] = $feature['start'];
  1730. $args[":fmax_$i"] = $feature['stop'];
  1731. $args[":strand_$i"] = $feature['strand'];
  1732. $args[":phase_$i"] = $feature['phase'] ? $feature['phase'] : NULL;
  1733. $args[":rank_$i"] = $rank;
  1734. }
  1735. // If we've reached the size of the batch then let's do the insert.
  1736. if ($i == $batch_size or $total == $num_features) {
  1737. if (count($args) > 0) {
  1738. $sql = rtrim($sql, ",\n");
  1739. $sql = $init_sql . $sql;
  1740. chado_query($sql, $args);
  1741. }
  1742. $this->setItemsHandled($batch_num);
  1743. $batch_num++;
  1744. // Now reset all of the varables for the next batch.
  1745. $sql = '';
  1746. $i = 0;
  1747. $args = [];
  1748. }
  1749. }
  1750. }
  1751. /**
  1752. * Finds an organism from an organism attribute value.
  1753. */
  1754. private function findOrganism($organism_attr, $line_num) {
  1755. if (array_key_exists($organism_attr, $this->organism_lookup)) {
  1756. return $this->organism_lookup[$organism_attr];
  1757. }
  1758. // Get the organism object.
  1759. [$genus, $species] = explode(':', $organism_attr, 2);
  1760. $organism = new ChadoRecord('organism');
  1761. $organism->setValues([
  1762. 'genus' => $genus,
  1763. 'species' => $species
  1764. ]);
  1765. $num_found = $organism->find();
  1766. if ($num_found == 1){
  1767. $this->organism_lookup[$organism_attr] = $organism->getID();
  1768. return $organism->getID();
  1769. }
  1770. if ($num_found > 1) {
  1771. throw new Exception(t('Multiple organisms were found for the "organism" attribute, %organism, on line %line_num',
  1772. ['%organism' => $organism_attr, '%line_num' => $line_num]));
  1773. }
  1774. if ($this->create_organism) {
  1775. $organism->insert();
  1776. $this->organism_lookup[$organism_attr] = $organism->getID();
  1777. $gff_feature['organism'] = $organism->getID();
  1778. return $organism->getID();
  1779. }
  1780. return NULL;
  1781. }
  1782. /**
  1783. *
  1784. */
  1785. private function findSynonyms() {
  1786. $batch_size = 1000;
  1787. $num_features = count(array_keys($this->features));
  1788. $num_batches = (int) ($num_features / $batch_size) + 1;
  1789. $this->setItemsHandled(0);
  1790. $this->setTotalItems($num_batches);
  1791. $init_sql = "SELECT synonym_id, name FROM {synonym} WHERE \n";
  1792. $i = 0;
  1793. $j = 0;
  1794. $total = 0;
  1795. $batch_num = 1;
  1796. $sql = '';
  1797. $args = [];
  1798. $batch_synonyms = [];
  1799. foreach ($this->features as $uniquename => $feature) {
  1800. $i++;
  1801. $total++;
  1802. // Get all of the synonyms for this batch.
  1803. foreach ($feature['synonyms'] as $index => $synonym) {
  1804. $batch_synonyms[] = $synonym;
  1805. }
  1806. // If we've reached the size of the batch then let's do the select
  1807. if ($i == $batch_size or $total == $num_features) {
  1808. $batch_synonyms = array_unique($batch_synonyms);
  1809. foreach ($batch_synonyms as $synonym) {
  1810. $j++;
  1811. if (!array_key_exists($synonym, $this->synonym_lookup)) {
  1812. $this->synonym_lookup[$synonym] = NULL;
  1813. }
  1814. if (!$this->synonym_lookup[$synonym]) {
  1815. $sql .= "(type_id = :type_id_$j AND name = :name_$j) OR\n";
  1816. $args[":type_id_$j"] = $this->exact_syn->cvterm_id;
  1817. $args[":name_$j"] = $synonym;
  1818. }
  1819. }
  1820. if (count($args) > 0) {
  1821. $sql = rtrim($sql, " OR\n");
  1822. $sql = $init_sql . $sql;
  1823. $results = chado_query($sql, $args);
  1824. while ($synonym = $results->fetchObject()) {
  1825. $this->synonym_lookup[$synonym->name] = $synonym->synonym_id;
  1826. }
  1827. }
  1828. $this->setItemsHandled($batch_num);
  1829. $batch_num++;
  1830. // Now reset all of the varables for the next batch.
  1831. $sql = '';
  1832. $i = 0;
  1833. $j = 0;
  1834. $args = [];
  1835. $batch_synonyms = [];
  1836. }
  1837. }
  1838. }
  1839. /**
  1840. *
  1841. */
  1842. private function insertSynonyms() {
  1843. $batch_size = 1000;
  1844. $num_synonyms = count(array_keys($this->synonym_lookup));
  1845. $num_batches = (int) ($num_synonyms / $batch_size) + 1;
  1846. $this->setItemsHandled(0);
  1847. $this->setTotalItems($num_batches);
  1848. $init_sql = "INSERT INTO {synonym} (type_id, name, synonym_sgml) VALUES\n";
  1849. $i = 0;
  1850. $total = 0;
  1851. $batch_num = 1;
  1852. $sql = '';
  1853. $args = [];
  1854. foreach ($this->synonym_lookup as $synonym => $synonym_id) {
  1855. $i++;
  1856. $total++;
  1857. // Only do an insert if this dbxref doesn't already exist in the databse.
  1858. if (!$synonym_id) {
  1859. $sql .= "(:type_id_$i,:name_$i, ''),\n";
  1860. $args[":type_id_$i"] = $this->exact_syn->cvterm_id;
  1861. $args[":name_$i"] = $synonym;
  1862. }
  1863. // If we've reached the size of the batch then let's do the insert.
  1864. if ($i == $batch_size or $total == $num_synonyms) {
  1865. if (count($args) > 0) {
  1866. $sql = rtrim($sql, ",\n");
  1867. $sql = $init_sql . $sql;
  1868. chado_query($sql, $args);
  1869. }
  1870. $this->setItemsHandled($batch_num);
  1871. $batch_num++;
  1872. // Now reset all of the varables for the next batch.
  1873. $sql = '';
  1874. $i = 0;
  1875. $args = [];
  1876. }
  1877. }
  1878. // Now we need to retrieve the synonyms IDs.
  1879. $this->findSynonyms();
  1880. }
  1881. /**
  1882. *
  1883. */
  1884. private function insertFeatureSynonyms(){
  1885. $batch_size = 1000;
  1886. $num_features = count(array_keys($this->features));
  1887. $num_batches = (int) ($num_features / $batch_size) + 1;
  1888. $this->setItemsHandled(0);
  1889. $this->setTotalItems($num_batches);
  1890. $init_sql = "INSERT INTO {feature_synonym} (synonym_id, feature_id, pub_id) VALUES \n";
  1891. $i = 0;
  1892. $j = 0;
  1893. $total = 0;
  1894. $batch_num = 1;
  1895. $args = [];
  1896. foreach ($this->features as $feature) {
  1897. $total++;
  1898. // If the feature is not skipped
  1899. if (!$feature['skipped']) {
  1900. $i++;
  1901. // Handle all of the synonyms for this feature.
  1902. foreach (array_unique($feature['synonyms']) as $synonym) {
  1903. $j++;
  1904. $sql .= "(:synonym_id_$j, :feature_id_$j, :pub_id_$j),\n";
  1905. $synonym_id = $this->synonym_lookup[$synonym];
  1906. $args[":synonym_id_$j"] = $this->synonym_lookup[$synonym];
  1907. $args[":feature_id_$j"] = $feature['feature_id'];
  1908. $args[":pub_id_$j"] = $this->null_pub->pub_id;
  1909. }
  1910. }
  1911. // If we've reached the size of the batch then let's do the insert.
  1912. if ($i == $batch_size or $total == $num_features) {
  1913. if (count($args) > 0) {
  1914. $sql = rtrim($sql, ",\n");
  1915. $sql = $init_sql . $sql;
  1916. chado_query($sql, $args);
  1917. }
  1918. $this->setItemsHandled($batch_num);
  1919. $batch_num++;
  1920. // Now reset all of the varables for the next batch.
  1921. $sql = '';
  1922. $i = 0;
  1923. $j = 0;
  1924. $args = [];
  1925. }
  1926. }
  1927. }
  1928. /**
  1929. * Retrieves the residues for a given feature.
  1930. *
  1931. */
  1932. private function getResidues($feature, $is_landmark = FALSE) {
  1933. return '';
  1934. }
  1935. /**
  1936. * Determines the name for a feature using the ID and name attributes.
  1937. *
  1938. * @param $feature_attrs
  1939. * The associative array of attributes for the feature.
  1940. *
  1941. * @param $type
  1942. * The type of feature.
  1943. *
  1944. * @return array
  1945. * An associative array with 'uniquename' and 'name' keys.
  1946. */
  1947. private function getFeatureName($attrs, $type, $landmark_name, $fmin, $fmax) {
  1948. $uniquename = '';
  1949. $name = '';
  1950. // If there is no ID or name then try to create a name and ID.
  1951. if (!array_key_exists('ID', $attrs) and !array_key_exists('name', $attrs)) {
  1952. // Check if an alternate ID field is suggested, if so, then use
  1953. // that for the name.
  1954. if (array_key_exists($this->alt_id_attr, $attrs)) {
  1955. $uniquename = $attrs[$this->alt_id_attr][0];
  1956. $name = $uniquename;
  1957. }
  1958. // If the row has a parent then generate a unqiue ID
  1959. elseif (array_key_exists('Parent', $attrs)) {
  1960. $uniquename = $attrs['Parent'][0] . "-" . $type . "-" .
  1961. $landmark_name . ":" . ($fmin + 1) . ".." . $fmax;
  1962. $name = $attrs['Parent'][0] . "-" . $type;
  1963. }
  1964. // Generate a unique name based on the type and location
  1965. // and set the name to simply be the type.
  1966. else {
  1967. $uniquename = $type . "-" . $landmark_name . ":" . ($fmin + 1) . ".." . $fmax;
  1968. $name = $type . "-" . $landmark_name;
  1969. }
  1970. }
  1971. elseif (!array_key_exists('Name', $attrs)) {
  1972. $uniquename = $attrs['ID'][0];
  1973. $name = $attrs['ID'][0];
  1974. }
  1975. elseif (!array_key_exists('ID', $attrs)) {
  1976. $uniquename = $attrs['Name'][0];
  1977. $name = $attrs['Name'][0];
  1978. }
  1979. else {
  1980. $uniquename = $attrs['ID'][0];
  1981. $name = $attrs['Name'][0];
  1982. }
  1983. // Does this uniquename already exist? This can happen for subfeatures
  1984. // (e.g. CDS features) that have multiple components but are really
  1985. // all the same thing.
  1986. if (array_key_exists($uniquename, $this->features)) {
  1987. if (array_key_exists('Parent', $attrs)) {
  1988. // Iterate through the list of similar IDs and see how many we have
  1989. // then add a numeric suffix.
  1990. $i = 2;
  1991. while (array_key_exists($uniquename . "_" . $i, $this->features)) {
  1992. $i++;
  1993. }
  1994. $uniquename = $uniquename . "_" . $i;
  1995. }
  1996. else {
  1997. throw new Exception(t("A feature with the same ID exists multiple times: !uname", ['!uname' => $uniquename]));
  1998. }
  1999. }
  2000. return [
  2001. 'name' => $name,
  2002. 'uniquename' => $uniquename,
  2003. ];
  2004. }
  2005. /**
  2006. * Load the derives from attribute for a gff3 feature
  2007. *
  2008. * @param $feature
  2009. * @param $subject
  2010. * @param $organism
  2011. *
  2012. * @ingroup gff3_loader
  2013. */
  2014. private function loadDerivesFromOld($feature, $cvterm, $object,
  2015. $organism, $fmin, $fmax) {
  2016. $type = $cvterm->name;
  2017. $derivesfrom_term = $this->getCvterm('derives_from');
  2018. // First look for the object feature in the temp table to get it's type.
  2019. $values = [
  2020. 'organism_id' => $organism->organism_id,
  2021. 'uniquename' => $object,
  2022. ];
  2023. $result = chado_select_record('tripal_gff_temp', ['type_name'], $values);
  2024. $type_id = NULL;
  2025. if (count($result) > 0) {
  2026. $type_id = $this->getCvterm($result[0]->type_name)->cvterm_id ?? NULL;
  2027. }
  2028. // If the object wasn't in the temp table then look for it in the
  2029. // feature table and get it's type.
  2030. if (!$type_id) {
  2031. $result = chado_select_record('feature', ['type_id'], $values);
  2032. if (count($result) > 1) {
  2033. $this->logMessage("Cannot find feature type for, '!subject' , in 'derives_from' relationship. Multiple matching features exist with this uniquename.",
  2034. ['!subject' => $object], TRIPAL_WARNING);
  2035. return;
  2036. }
  2037. else {
  2038. if (count($result) == 0) {
  2039. $this->logMessage("Cannot find feature type for, '!subject' , in 'derives_from' relationship.",
  2040. ['!subject' => $object], TRIPAL_WARNING);
  2041. return '';
  2042. }
  2043. else {
  2044. $type_id = $result->type_id;
  2045. }
  2046. }
  2047. }
  2048. // Get the object feature.
  2049. $match = [
  2050. 'organism_id' => $organism->organism_id,
  2051. 'uniquename' => $object,
  2052. 'type_id' => $type_id,
  2053. ];
  2054. $ofeature = chado_select_record('feature', ['feature_id'], $match);
  2055. if (count($ofeature) == 0) {
  2056. $this->logMessage("Could not add 'Derives_from' relationship " .
  2057. "for %uniquename and %subject. Subject feature, '%subject', " .
  2058. "cannot be found.", [
  2059. '%uniquename' => $feature->getValue('uniquename'),
  2060. '%subject' => $subject,
  2061. ], TRIPAL_ERROR);
  2062. return;
  2063. }
  2064. // If this feature is a protein then add it to the tripal_gffprotein_temp.
  2065. if ($type == 'protein' or $type == 'polypeptide') {
  2066. $values = [
  2067. 'feature_id' => $feature->getID(),
  2068. 'parent_id' => $ofeature[0]->feature_id,
  2069. 'fmin' => $fmin,
  2070. 'fmax' => $fmax,
  2071. ];
  2072. $result = chado_insert_record('tripal_gffprotein_temp', $values);
  2073. if (!$result) {
  2074. throw new Exception(t("Cound not save record in temporary protein table, Cannot continue.", []));
  2075. }
  2076. }
  2077. // Now check to see if the relationship already exists. If it does
  2078. // then just return.
  2079. $values = [
  2080. 'object_id' => $ofeature[0]->feature_id,
  2081. 'subject_id' => $feature->getID(),
  2082. 'type_id' => $derivesfrom_term->cvterm_id,
  2083. 'rank' => 0,
  2084. ];
  2085. $rel = chado_select_record('feature_relationship', ['*'], $values);
  2086. if (count($rel) > 0) {
  2087. return;
  2088. }
  2089. // finally insert the relationship if it doesn't exist
  2090. $ret = chado_insert_record('feature_relationship', $values, array(
  2091. 'skip_validation' => TRUE,
  2092. ));
  2093. if (!$ret) {
  2094. $this->logMessage("Could not add 'Derives_from' relationship for :uniquename and :subject.",
  2095. [
  2096. ':uniquename' => $feature->getValue('uniquename'),
  2097. ':subject' => $subject,
  2098. ], TRIPAL_WARNING);
  2099. }
  2100. }
  2101. /**
  2102. * Create the feature record & link it to it's analysis
  2103. *
  2104. * @param $organism
  2105. * @param $analysis_id
  2106. * @param $cvterm
  2107. * @param $uniquename
  2108. * @param $name
  2109. * @param $residues
  2110. * @param $is_analysis
  2111. * @param $is_obsolete
  2112. * @param $add_only
  2113. * @param $score
  2114. *
  2115. * @ingroup gff3_loader
  2116. */
  2117. private function insertFeature($organism, $analysis, $cvterm, $uniquename,
  2118. $name, $residues, $is_analysis = 'f', $is_obsolete = 'f', $add_only, $score) {
  2119. if (strcmp($is_obsolete, 'f') == 0 or $is_obsolete == 0) {
  2120. $is_obsolete = 'FALSE';
  2121. }
  2122. if (strcmp($is_obsolete, 't') == 0 or $is_obsolete == 1) {
  2123. $is_obsolete = 'TRUE';
  2124. }
  2125. if (strcmp($is_analysis, 'f') == 0 or $is_analysis == 0) {
  2126. $is_analysis = 'FALSE';
  2127. }
  2128. if (strcmp($is_analysis, 't') == 0 or $is_analysis == 1) {
  2129. $is_analysis = 'TRUE';
  2130. }
  2131. // Check to see if the feature already exists.
  2132. $feature = new ChadoRecord('feature');
  2133. $feature->setValues([
  2134. 'organism_id' => $organism->getValue('organism_id'),
  2135. 'uniquename' => $uniquename,
  2136. 'type_id' => $cvterm->getValue('cvterm_id'),
  2137. ]);
  2138. $num_matches = $feature->find();
  2139. // Insert the feature if it does not exist otherwise perform an update.
  2140. if ($num_matches == 0) {
  2141. $feature->setValue('name', $name);
  2142. $feature->setValue('md5checksum', md5($residues));
  2143. $feature->setValue('is_analysis', $is_analysis);
  2144. $feature->setValue('is_obsolete', $is_obsolete);
  2145. try {
  2146. $feature->insert();
  2147. }
  2148. catch (Exception $e) {
  2149. $this->logMessage("Failed to insert feature '$uniquename' (" . $cvterm->getValue('name') . ").", [], TRIPAL_WARNING);
  2150. return 0;
  2151. }
  2152. }
  2153. elseif (!$add_only) {
  2154. if ($num_matches > 1) {
  2155. $this->logMessage("Failed to update feature '$uniquename' (" . $cvterm->getValue('name') . "). More than one feature exists with these criteria", [], TRIPAL_WARNING);
  2156. return 0;
  2157. }
  2158. $feature->setValue('name', $name);
  2159. $feature->setValue('md5checksum', md5($residues));
  2160. $feature->setValue('is_analysis', $is_analysis);
  2161. $feature->setValue('is_obsolete', $is_obsolete);
  2162. try {
  2163. $feature->update();
  2164. }
  2165. catch (Exception $e) {
  2166. $this->logMessage("Failed to update feature '$uniquename' (" . $cvterm->getValue('name') . ").", [], TRIPAL_WARNING);
  2167. return 0;
  2168. }
  2169. }
  2170. else {
  2171. // The feature exists and we don't want to update it so return
  2172. // a value of 0. This will stop all downstream property additions
  2173. return $feature;
  2174. }
  2175. // Add the analysisfeature entry to the analysisfeature table if
  2176. // it doesn't already exist.
  2177. $af = new ChadoRecord('analysisfeature');
  2178. $af->setValues([
  2179. 'analysis_id' => $analysis->getValue('analysis_id'),
  2180. 'feature_id' => $feature->getID(),
  2181. ]);
  2182. $num_afs = $af->find();
  2183. if ($num_afs == 0) {
  2184. // if a score is available then set that to be the significance field
  2185. if (strcmp($score, '.') != 0) {
  2186. $af->setValue('significance', $score);
  2187. }
  2188. try {
  2189. $af->insert();
  2190. }
  2191. catch (Exception $e) {
  2192. $this->logMessage("Could not add analysisfeature record: " . $analysis->getValue('analysis_id') . ", " . $feature->getID() . ". " . $e->getMessage(), [], TRIPAL_WARNING);
  2193. }
  2194. }
  2195. else {
  2196. // if a score is available then set that to be the significance field
  2197. $new_vals = [];
  2198. if (strcmp($score, '.') != 0) {
  2199. $af->setValue('significance', $score);
  2200. }
  2201. else {
  2202. $af->setValue('significance', '__NULL__');
  2203. }
  2204. if (!$add_only) {
  2205. try {
  2206. $af->update();
  2207. }
  2208. catch (Exception $e) {
  2209. $this->logMessage("Could not update analysisfeature record: $analysis_id, " . $feature->getID() . ". " . $e->getMessage(), [], TRIPAL_WARNING);
  2210. }
  2211. }
  2212. }
  2213. return $feature;
  2214. }
  2215. /**
  2216. * Load the target attribute of a gff3 record
  2217. *
  2218. * @param $feature
  2219. * @param $tags
  2220. * @param $target_organism_id
  2221. * @param $target_type
  2222. * @param $create_target
  2223. * @param $attr_locgroup
  2224. *
  2225. * @ingroup gff3_loader
  2226. */
  2227. private function loadTarget($feature, $tags, $target_organism_id, $target_type, $create_target, $attr_locgroup) {
  2228. // format is: "target_id start end [strand]", where strand is optional and may be "+" or "-"
  2229. $matched = preg_match('/^(.*?)\s+(\d+)\s+(\d+)(\s+[\+|\-])*$/', trim($tags['Target'][0]), $matches);
  2230. // the organism and type of the target may also be specified as an attribute. If so, then get that
  2231. // information
  2232. $gff_target_organism = array_key_exists('target_organism', $tags) ? $tags['target_organism'][0] : '';
  2233. $gff_target_type = array_key_exists('target_type', $tags) ? $tags['target_type'][0] : '';
  2234. // if we have matches and the Target is in the correct format then load the alignment
  2235. if ($matched) {
  2236. $target_feature = $matches[1];
  2237. $start = $matches[2];
  2238. $end = $matches[3];
  2239. // if we have an optional strand, convert it to a numeric value.
  2240. if (!empty($matches[4])) {
  2241. if (preg_match('/^\+$/', trim($matches[4]))) {
  2242. $target_strand = 1;
  2243. }
  2244. elseif (preg_match('/^\-$/', trim($matches[4]))) {
  2245. $target_strand = -1;
  2246. }
  2247. else {
  2248. $target_strand = 0;
  2249. }
  2250. }
  2251. else {
  2252. $target_strand = 0;
  2253. }
  2254. $target_fmin = $start - 1;
  2255. $target_fmax = $end;
  2256. if ($end < $start) {
  2257. $target_fmin = $end - 1;
  2258. $target_fmax = $start;
  2259. }
  2260. // default the target organism to be the value passed into the function, but if the GFF
  2261. // file species the target organism then use that instead.
  2262. $t_organism_id = $target_organism_id;
  2263. if ($gff_target_organism) {
  2264. // get the genus and species
  2265. $success = preg_match('/^(.*?):(.*?)$/', $gff_target_organism, $matches);
  2266. if ($success) {
  2267. $values = [
  2268. 'genus' => $matches[1],
  2269. 'species' => $matches[2],
  2270. ];
  2271. $torganism = chado_select_record('organism', ['organism_id'], $values);
  2272. if (count($torganism) == 1) {
  2273. $t_organism_id = $torganism[0]->organism_id;
  2274. }
  2275. else {
  2276. $this->logMessage("Cannot find organism for target %target.",
  2277. ['%target' => $gff_target_organism], TRIPAL_WARNING);
  2278. $t_organism_id = '';
  2279. }
  2280. }
  2281. else {
  2282. $this->logMessage("The target_organism attribute is improperly formatted: %target. " .
  2283. "It should be target_organism=genus:species.",
  2284. ['%target' => $gff_target_organism], TRIPAL_WARNING);
  2285. $t_organism_id = '';
  2286. }
  2287. }
  2288. // default the target type to be the value passed into the function, but if the GFF file
  2289. // species the target type then use that instead
  2290. $t_type_id = '';
  2291. if ($target_type) {
  2292. $values = [
  2293. 'name' => $target_type,
  2294. 'cv_id' => [
  2295. 'name' => 'sequence',
  2296. ],
  2297. ];
  2298. $type = chado_select_record('cvterm', ['cvterm_id'], $values);
  2299. if (count($type) == 1) {
  2300. $t_type_id = $type[0]->cvterm_id;
  2301. }
  2302. else {
  2303. throw new Exception(t("The target type does not exist in the sequence ontology: %type. ",
  2304. ['%type' => $target_type]));
  2305. }
  2306. }
  2307. if ($gff_target_type) {
  2308. $values = [
  2309. 'name' => $gff_target_type,
  2310. 'cv_id' => [
  2311. 'name' => 'sequence',
  2312. ],
  2313. ];
  2314. // get the cvterm_id for the target type
  2315. $type = chado_select_record('cvterm', ['cvterm_id'], $values);
  2316. if (count($type) == 1) {
  2317. $t_type_id = $type[0]->cvterm_id;
  2318. }
  2319. else {
  2320. // check to see if this is a synonym
  2321. $sql = "
  2322. SELECT CVTS.cvterm_id
  2323. FROM {cvtermsynonym} CVTS
  2324. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = CVTS.cvterm_id
  2325. INNER JOIN {cv} CV ON CV.cv_id = CVT.cv_id
  2326. WHERE CV.name = 'sequence' and CVTS.synonym = :synonym
  2327. ";
  2328. $synonym = chado_query($sql, [':synonym' => $gff_target_type])->fetchObject();
  2329. if ($synonym) {
  2330. $t_type_id = $synonym->cvterm_id;
  2331. }
  2332. else {
  2333. $this->logMessage("The target_type attribute does not exist in the sequence ontology: %type.",
  2334. ['%type' => $gff_target_type], TRIPAL_WARNING);
  2335. $t_type_id = '';
  2336. }
  2337. }
  2338. }
  2339. // we want to add a featureloc record that uses the target feature as the srcfeature (landmark)
  2340. // and the landmark as the feature.
  2341. $this->loadFeatureLoc($feature, NULL, $target_feature, $target_fmin,
  2342. $target_fmax, $target_strand, NULL, NULL, NULL, NULL,
  2343. $attr_locgroup, $t_type_id, $t_organism_id, $create_target, TRUE);
  2344. }
  2345. // the target attribute is not correctly formatted
  2346. else {
  2347. $this->logMessage("Could not add 'Target' alignment as it is improperly formatted: '%target'",
  2348. ['%target' => $tags['Target'][0]], TRIPAL_ERROR);
  2349. }
  2350. }
  2351. }