GFF3Importer.inc 98 KB

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