GFF3Importer.inc 120 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424
  1. <?php
  2. class GFF3Importer extends TripalImporter {
  3. /**
  4. * The name of this loader. This name will be presented to the site
  5. * user.
  6. */
  7. public static $name = 'Chado GFF3 File Loader';
  8. /**
  9. * The machine name for this loader. This name will be used to construct
  10. * the URL for the loader.
  11. */
  12. public static $machine_name = 'chado_gff3_loader';
  13. /**
  14. * A brief description for this loader. This description will be
  15. * presented to the site user.
  16. */
  17. public static $description = 'Import a GFF3 file into Chado';
  18. /**
  19. * An array containing the extensions of allowed file types.
  20. */
  21. public static $file_types = ['gff', 'gff3'];
  22. /**
  23. * Provides information to the user about the file upload. Typically this
  24. * may include a description of the file types allowed.
  25. */
  26. public static $upload_description = 'Please provide the GFF3 file.';
  27. /**
  28. * The title that should appear above the upload button.
  29. */
  30. public static $upload_title = 'GFF3 File';
  31. /**
  32. * Text that should appear on the button at the bottom of the importer
  33. * form.
  34. */
  35. public static $button_text = 'Import GFF3 file';
  36. /**
  37. * The path to the GFF3 file.
  38. */
  39. private $gff_file = NULL;
  40. /**
  41. * The file handle for the GFF3 file.
  42. */
  43. private $gff_file_h = NULL;
  44. /**
  45. * The organism ID for this GFF file.
  46. */
  47. private $organism_id = NULL;
  48. /**
  49. * The organism ChadoRecord object that corresponds to the $organism_id value.
  50. */
  51. private $organism = NULL;
  52. /**
  53. * An array of organism records for quick lookup.
  54. */
  55. private $organism_lookup = NULL;
  56. /**
  57. * The analysis ID for this GFF file
  58. */
  59. private $analysis_id = NULL;
  60. /**
  61. * The analysis ChadoRecord object that corresponds to the $analysis_id value.
  62. */
  63. private $analysis = NULL;
  64. /**
  65. * A flag indicating if only new items should be added (no updates)
  66. */
  67. private $add_only = NULL;
  68. /**
  69. * A flag indicting if only existing items should be updated.
  70. */
  71. private $update = TRUE;
  72. /**
  73. * If the GFF file contains a 'Target' attribute then the feature and the
  74. * target will have an alignment created, but to find the proper target
  75. * feature the target organism must also be known. If different from the
  76. * organism specified for the GFF file, then use this argument to specify
  77. * the target organism. Only use this argument if all target sequences
  78. * belong to the same species. If the targets in the GFF file belong to
  79. * multiple different species then the organism must be specified using the
  80. * 'target_organism=genus:species' attribute in the GFF file. Default is
  81. * NULL.
  82. */
  83. private $target_organism_id = NULL;
  84. /**
  85. * If the GFF file contains a 'Target' attribute then the feature and the
  86. * target will have an alignment created, but to find the proper target
  87. * feature the target organism must also be known. This can be used to
  88. * specify the target feature type to help with identification of the
  89. * target feature. Only use this argument if all target sequences types are
  90. * the same. If the targets are of different types then the type must be
  91. * specified using the 'target_type=type' attribute in the GFF file. This
  92. * must be a valid Sequence Ontology (SO) term. Default is NULL
  93. */
  94. private $target_type = NULL;
  95. /**
  96. * A flag indicating if the target feature should be created. If FALSE
  97. * then it should already exist.
  98. */
  99. private $create_target = FALSE;
  100. /**
  101. * Set this to the line in the GFF file where importing should start. This
  102. * is useful for testing and debugging GFF files that may have problems and
  103. * you want to start at a particular line to speed testing. Default = 1
  104. */
  105. private $start_line = 1;
  106. /**
  107. * During parsing of the GFF file this keeps track of the current line
  108. * number.
  109. */
  110. private $current_line = 0;
  111. /**
  112. * A Sequence Ontology term name for the landmark sequences in the GFF
  113. * file (e.g. 'chromosome'), if the GFF file contains a '##sequence-region'
  114. * line that describes the landmark sequences. Default = ''
  115. */
  116. private $landmark_type = '';
  117. /**
  118. * The ChadoRecord object for the landmark type cvterm.
  119. */
  120. private $landmark_cvterm = NULL;
  121. /**
  122. * Regular expression to pull out the mRNA name.
  123. */
  124. private $re_mrna = '';
  125. /**
  126. * Regular expression to pull out the protein name.
  127. */
  128. private $re_protein = '';
  129. /**
  130. * A flag that indicates if a protein record should be created.
  131. * @var integer
  132. */
  133. private $skip_protein = 0;
  134. /**
  135. * Sometimes lines in the GFF file are missing the required ID attribute
  136. * that specifies the unique name of the feature. If so, you may specify
  137. * the name of an existing attribute to use for the ID.
  138. */
  139. private $alt_id_attr = '';
  140. /**
  141. * The Tripal GFF loader supports the "organism" attribute. This allows
  142. * features of a different organism to be aligned to the landmark sequence
  143. * of another species. The format of the attribute is
  144. * "organism=[genus]:[species]", where [genus] is the organism's genus and
  145. * [species] is the species name. Check this box to automatically add the
  146. * organism to the database if it does not already exists. Otherwise lines
  147. * with an oraganism attribute where the organism is not present in the
  148. * database will be skipped.
  149. */
  150. private $create_organism = FALSE;
  151. /**
  152. * An array that stores CVterms that have been looked up so we don't have
  153. * to do the database query every time.
  154. */
  155. private $feature_cvterm_lookup = [];
  156. /**
  157. * An array that stores CVterms that have been looked up so we don't have
  158. * to do the database query every time.
  159. */
  160. private $featureprop_cvterm_lookup = [];
  161. /**
  162. * Holds the CV term for the "exact" synonym.
  163. */
  164. private $exact_syn = NULL;
  165. /**
  166. * Holds the object for the null publication record.
  167. */
  168. private $null_pub = NULL;
  169. /**
  170. * An array the stores existing features in the database for the organism
  171. * and feature types in the database. This is used for quick lookups
  172. * to prevent violating the unique constraints on a bulk insert.
  173. */
  174. private $feature_lookup = [];
  175. /**
  176. * The list of features from the GFF3 file. Each element is an
  177. * associative array of the columns from the GFF3 file, with the attribute
  178. * field being an associative array of key/value pairs.
  179. */
  180. private $features = [];
  181. /**
  182. * A mapping of features to their parents.
  183. */
  184. private $relationships = [
  185. 'Parent' => [],
  186. 'Child' => [],
  187. ];
  188. /**
  189. * An associatiave array containing the pointers to the FASTA sequences
  190. * in the GFF file. We don't want to load these into memory as they
  191. * may be too big!
  192. */
  193. private $residue_index = [];
  194. /**
  195. * An array that stores Landmarks that have been looked up so we don't have
  196. * to do the database query every time.
  197. */
  198. private $landmark_lookup = [];
  199. /**
  200. * A controlled vocabulary ChadoRecord object. This is the CV that will be
  201. * used to for feature properties.
  202. */
  203. private $feature_prop_cv = NULL;
  204. /**
  205. * A controlled vocabulary ChadoRecord object. This is the CV that will be
  206. * used to for feature properties.
  207. */
  208. private $feature_cv = NULL;
  209. /**
  210. * @see TripalImporter::form()
  211. */
  212. public function form($form, &$form_state) {
  213. // get the list of organisms
  214. $sql = "SELECT * FROM {organism} ORDER BY genus, species";
  215. $org_rset = chado_query($sql);
  216. $organisms = [];
  217. $organisms[''] = '';
  218. while ($organism = $org_rset->fetchObject()) {
  219. $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
  220. }
  221. $form['organism_id'] = [
  222. '#title' => t('Organism'),
  223. '#type' => t('select'),
  224. '#description' => t("Choose the organism to which these sequences are associated"),
  225. '#required' => TRUE,
  226. '#options' => $organisms,
  227. ];
  228. // Advanced Options
  229. $form['advanced'] = [
  230. '#type' => 'fieldset',
  231. '#title' => t('Additional Options'),
  232. '#collapsible' => TRUE,
  233. '#collapsed' => TRUE,
  234. ];
  235. $form['advanced']['line_number'] = [
  236. '#type' => 'textfield',
  237. '#title' => t('Start Line Number'),
  238. '#description' => t('Enter the line number in the GFF file where you would like to begin processing. The
  239. first line is line number 1. This option is useful for examining loading problems with large GFF files.'),
  240. '#size' => 10,
  241. ];
  242. $form['advanced']['landmark_type'] = [
  243. '#title' => t('Landmark Type'),
  244. '#type' => t('textfield'),
  245. '#description' => t("Optional. Use this field to specify a Sequence Ontology type
  246. for the landmark sequences in the GFF fie (e.g. 'chromosome'). If the GFF file
  247. contains a '##sequence-region' line that describes the landmark sequences to
  248. which all others are aligned and a type is provided here then the features
  249. will be created if they do not already exist. If they do exist then this
  250. field is not used."),
  251. ];
  252. $form['advanced']['alt_id_attr'] = [
  253. '#title' => t('ID Attribute'),
  254. '#type' => t('textfield'),
  255. '#description' => t("Optional. Sometimes lines in the GFF file are missing the
  256. required ID attribute that specifies the unique name of the feature, but there
  257. may be another attribute that can uniquely identify the feature. If so,
  258. you may specify the name of the attribute to use for the name."),
  259. ];
  260. $form['advanced']['skip_protein'] = [
  261. '#type' => 'checkbox',
  262. '#title' => t('Skip automatic protein creation'),
  263. '#required' => FALSE,
  264. '#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.'),
  265. '#default_value' => 0,
  266. ];
  267. $form['advanced']['protein_names'] = [
  268. '#type' => 'fieldset',
  269. '#title' => t('Protein Names'),
  270. '#collapsible' => TRUE,
  271. '#collapsed' => FALSE,
  272. '#weight' => 5,
  273. ];
  274. $form['advanced']['protein_names']['re_help'] = [
  275. '#type' => 'item',
  276. '#markup' => t('A regular expression is an advanced method for extracting information from a string of text.
  277. If your GFF3 file does not contain polypeptide (or protein) features, but contains CDS features, proteins will be automatically created.
  278. By default the loader will give each protein a name based on the name of the corresponding mRNA followed by the "-protein" suffix.
  279. If you want to customize the name of the created protein, you can use the following regex.'),
  280. ];
  281. $form['advanced']['protein_names']['re_mrna'] = [
  282. '#type' => 'textfield',
  283. '#title' => t('Regular expression for the mRNA name'),
  284. '#required' => FALSE,
  285. '#description' => t('Enter the regular expression that will extract portions of
  286. the mRNA unique name. For example, for a
  287. mRNA with a unique name finishing by -RX (e.g. SPECIES0000001-RA),
  288. the regular expression would be, "^(.*?)-R([A-Z]+)$".'),
  289. ];
  290. $form['advanced']['protein_names']['re_protein'] = [
  291. '#type' => 'textfield',
  292. '#title' => t('Replacement string for the protein name'),
  293. '#required' => FALSE,
  294. '#description' => t('Enter the replacement string that will be used to create
  295. the protein name based on the mRNA regular expression. For example, for a
  296. mRNA regular expression "^(.*?)-R()[A-Z]+)$", the corresponding protein regular
  297. expression would be "$1-P$2".'),
  298. ];
  299. $form['advanced']['add_only'] = [
  300. '#type' => 'checkbox',
  301. '#title' => t('Import only new features'),
  302. '#required' => FALSE,
  303. '#description' => t('The job will skip features in the GFF file that already
  304. exist in the database and import only new features.'),
  305. ];
  306. $form['advanced']['update'] = [
  307. '#type' => 'checkbox',
  308. '#title' => t('Import all and update'),
  309. '#required' => FALSE,
  310. '#default_value' => 'checked',
  311. '#description' => t('Existing features will be updated and new features will be added. Attributes
  312. for a feature that are not present in the GFF but which are present in the
  313. database will not be altered.'),
  314. '#default_value' => 1,
  315. ];
  316. // SPF: there are bugs in refreshing and removing features. The bugs arise
  317. // if a feature in the GFF does not have a uniquename. GenSAS will auto
  318. // generate this uniquename and it will not be the same as a previous
  319. // load because it uses the date. This causes orphaned CDS/exons, UTRs
  320. // to be left behind during a delete or refresh. So, the short term
  321. // fix is to remove these options.
  322. // $form['import_options']['refresh']= array(
  323. // '#type' => 'checkbox',
  324. // '#title' => t('Import all and replace'),
  325. // '#required' => FALSE,
  326. // '#description' => t('Existing features will be updated and feature properties not
  327. // present in the GFF file will be removed.'),
  328. // );
  329. // $form['import_options']['remove']= array(
  330. // '#type' => 'checkbox',
  331. // '#title' => t('Delete features'),
  332. // '#required' => FALSE,
  333. // '#description' => t('Features present in the GFF file that exist in the database
  334. // will be removed rather than imported'),
  335. // );
  336. $form['advanced']['create_organism'] = [
  337. '#type' => 'checkbox',
  338. '#title' => t('Create organism'),
  339. '#required' => FALSE,
  340. '#description' => t('The Tripal GFF loader supports the "organism" attribute. This allows features of a
  341. different organism to be aligned to the landmark sequence of another species. The format of the
  342. attribute is "organism=[genus]:[species]", where [genus] is the organism\'s genus and [species] is the
  343. species name. Check this box to automatically add the organism to the database if it does not already exists.
  344. Otherwise lines with an oraganism attribute where the organism is not present in the database will be skipped.'),
  345. ];
  346. $form['advanced']['targets'] = [
  347. '#type' => 'fieldset',
  348. '#title' => t('Targets'),
  349. '#collapsible' => TRUE,
  350. '#collapsed' => FALSE,
  351. '#weight' => 1,
  352. ];
  353. $form['advanced']['targets']['adesc'] = [
  354. '#markup' => t("When alignments are represented in the GFF file (e.g. such as
  355. alignments of cDNA sequences to a whole genome, or blast matches), they are
  356. represented using two feature types: 'match' (or cDNA_match, EST_match, etc.)
  357. and 'match_part'. These features may also have a 'Target' attribute to
  358. specify the sequence that is being aligned.
  359. However, the organism to which the aligned sequence belongs may not be present in the
  360. GFF file. Here you can specify the organism and feature type of the target sequences.
  361. The options here will apply to all targets unless the organism and type are explicity
  362. set in the GFF file using the 'target_organism' and 'target_type' attributes."),
  363. ];
  364. $form['advanced']['targets']['target_organism_id'] = [
  365. '#title' => t('Target Organism'),
  366. '#type' => t('select'),
  367. '#description' => t("Optional. Choose the organism to which target sequences belong.
  368. Select this only if target sequences belong to a different organism than the
  369. one specified above. And only choose an organism here if all of the target sequences
  370. belong to the same species. If the targets in the GFF file belong to multiple
  371. different species then the organism must be specified using the 'target_organism=genus:species'
  372. attribute in the GFF file."),
  373. '#options' => $organisms,
  374. ];
  375. $form['advanced']['targets']['target_type'] = [
  376. '#title' => t('Target Type'),
  377. '#type' => t('textfield'),
  378. '#description' => t("Optional. If the unique name for a target sequence is not unique (e.g. a protein
  379. and an mRNA have the same name) then you must specify the type for all targets in the GFF file. If
  380. the targets are of different types then the type must be specified using the 'target_type=type' attribute
  381. in the GFF file. This must be a valid Sequence Ontology (SO) term."),
  382. ];
  383. $form['advanced']['targets']['create_target'] = [
  384. '#type' => 'checkbox',
  385. '#title' => t('Create Target'),
  386. '#required' => FALSE,
  387. '#description' => t("If the target feature cannot be found, create one using the organism and type specified above, or
  388. using the 'target_organism' and 'target_type' fields specified in the GFF file. Values specified in the
  389. GFF file take precedence over those specified above."),
  390. ];
  391. return $form;
  392. }
  393. /**
  394. * @see TripalImporter::formValidate()
  395. */
  396. public function formValidate($form, &$form_state) {
  397. $organism_id = $form_state['values']['organism_id'];
  398. $target_organism_id = $form_state['values']['target_organism_id'];
  399. $target_type = trim($form_state['values']['target_type']);
  400. $create_target = $form_state['values']['create_target'];
  401. $create_organism = $form_state['values']['create_organism'];
  402. $add_only = $form_state['values']['add_only'];
  403. $update = $form_state['values']['update'];
  404. $refresh = 0; //$form_state['values']['refresh'];
  405. $remove = 0; //$form_state['values']['remove'];
  406. $line_number = trim($form_state['values']['line_number']);
  407. $landmark_type = trim($form_state['values']['landmark_type']);
  408. $alt_id_attr = trim($form_state['values']['alt_id_attr']);
  409. $re_mrna = trim($form_state['values']['re_mrna']);
  410. $re_protein = trim($form_state['values']['re_protein']);
  411. // @coder-ignore: there are no functions being called here
  412. if (($add_only AND ($update OR $refresh OR $remove)) OR
  413. ($update AND ($add_only OR $refresh OR $remove)) OR
  414. ($refresh AND ($update OR $add_only OR $remove)) OR
  415. ($remove AND ($update OR $refresh OR $add_only))) {
  416. form_set_error('add_only', t("Please select only one checkbox from the import options section"));
  417. }
  418. if ($line_number and !is_numeric($line_number) or $line_number < 0) {
  419. form_set_error('line_number', t("Please provide an integer line number greater than zero."));
  420. }
  421. if (!($re_mrna and $re_protein) and ($re_mrna or $re_protein)) {
  422. form_set_error('re_uname', t("You must provide both a regular expression for mRNA and a replacement string for protein"));
  423. }
  424. // check the regular expression to make sure it is valid
  425. set_error_handler(function () {
  426. }, E_WARNING);
  427. $result_re = preg_match("/" . $re_mrna . "/", NULL);
  428. $result = preg_replace("/" . $re_mrna . "/", $re_protein, NULL);
  429. restore_error_handler();
  430. if ($result_re === FALSE) {
  431. form_set_error('re_mrna', 'Invalid regular expression.');
  432. }
  433. else {
  434. if ($result === FALSE) {
  435. form_set_error('re_protein', 'Invalid replacement string.');
  436. }
  437. }
  438. }
  439. /**
  440. * @see TripalImporter::run()
  441. */
  442. public function run() {
  443. $arguments = $this->arguments['run_args'];
  444. $this->gff_file = $this->arguments['files'][0]['file_path'];
  445. // Set the private member variables of this class using the loader inputs.
  446. $this->organism_id = $arguments['organism_id'];
  447. $this->analysis_id = $arguments['analysis_id'];
  448. $this->add_only = $arguments['add_only'];
  449. $this->update = $arguments['update'];
  450. $this->target_organism_id = $arguments['target_organism_id'];
  451. $this->target_type = $arguments['target_type'];
  452. $this->create_target = $arguments['create_target'];
  453. $this->start_line = $arguments['line_number'];
  454. $this->landmark_type = $arguments['landmark_type'];
  455. $this->alt_id_attr = $arguments['alt_id_attr'];
  456. $this->create_organism = $arguments['create_organism'];
  457. $this->re_mrna = $arguments['re_mrna'];
  458. $this->re_protein = $arguments['re_protein'];
  459. $this->skip_protein = $arguments['skip_protein'];
  460. // Check to see if the file is located local to Drupal
  461. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $this->gff_file;
  462. if (!file_exists($dfile)) {
  463. $this->gff_file = $dfile;
  464. }
  465. // If the file is not local to Drupal check if it exists on the system.
  466. else if (!file_exists($this->gff_file)) {
  467. throw new Exception(t("Cannot find the file: !file", ['!file' => $this->gff_file]));
  468. }
  469. // Open the GFF3 file.
  470. $this->logMessage("Opening !gff_file", ['!gff_file' => $this->gff_file]);
  471. $this->gff_file_h = fopen($this->gff_file, 'r');
  472. if (!$this->gff_file_h) {
  473. throw new Exception(t("Cannot open file: !file", ['!file' => $this->gff_file]));
  474. }
  475. // Get the feature property CV object
  476. $this->feature_prop_cv = new ChadoRecord('cv');
  477. $this->feature_prop_cv->setValues(['name' => 'feature_property']);
  478. $num_found = $this->feature_prop_cv->find();
  479. if ($num_found == 0) {
  480. throw new Exception(t("Cannot find the 'feature_property' ontology'", []));
  481. }
  482. // Get the sequence CV object.
  483. $this->feature_cv = new ChadoRecord('cv');
  484. $this->feature_cv->setValues(['name' => 'sequence']);
  485. $num_found = $this->feature_cv->find();
  486. if ($num_found == 0) {
  487. throw new Exception(t("Cannot find the 'sequence' ontology'", []));
  488. }
  489. // Get the organism object.
  490. $this->organism = new ChadoRecord('organism');
  491. $this->organism->setValues(['organism_id' => $this->organism_id]);
  492. $num_found = $this->organism->find();
  493. if ($num_found == 0) {
  494. throw new Exception(t("Cannot find the specified organism for this GFF3 file."));
  495. }
  496. // Get the analysis object.
  497. $this->analysis = new ChadoRecord('analysis');
  498. $this->analysis->setValues(['analysis_id' => $this->analysis_id]);
  499. $num_found = $this->analysis->find();
  500. if ($num_found == 0) {
  501. throw new Exception(t("Cannot find the specified organism for this GFF3 file."));
  502. }
  503. // If a landmark type was provided then get that object.
  504. if ($this->landmark_type) {
  505. $this->landmark_cvterm = new ChadoRecord('cvterm');
  506. $this->landmark_cvterm->setValues([
  507. 'cv_id' => $this->feature_cv->getValue('cv_id'),
  508. 'name' => $this->landmark_type,
  509. ]);
  510. $num_found = $this->landmark_cvterm->find();
  511. if ($num_found == 0) {
  512. throw new Exception(t('Cannot find landmark feature type \'%landmark_type\'.', ['%landmark_type' => $this->landmark_type]));
  513. }
  514. }
  515. // Make sure we have the synonym records and null publication ready to go.
  516. $this->prepSynonms();
  517. $this->prepNullPub();
  518. // Load the GFF3.
  519. $this->logMessage("Step 1: Preloading GFF3 file...");
  520. $this->parseGFF3();
  521. $this->logMessage("Step 2: Loading features...");
  522. $this->loadFeatures();
  523. $this->logMessage("Step 3: Loading feature locations...");
  524. //$this->loadFeatureLocs();
  525. $this->logMessage("Step 4: Loading features properties...");
  526. //$this->loadFeatureProps();
  527. $this->logMessage("Step 5: Loading features synonyms (aliases)...");
  528. $this->loadAliases();
  529. }
  530. /**
  531. * Cleans up the temporary tables.
  532. *
  533. * These tables are used to temporarily store features from the GFF file.
  534. * This way the GFF entries can be out of order when loading.
  535. */
  536. private function prepTempTables() {
  537. // empty the temp tables
  538. $sql = "DELETE FROM {tripal_gff_temp}";
  539. chado_query($sql);
  540. $sql = "DELETE FROM {tripal_gffcds_temp}";
  541. chado_query($sql);
  542. $sql = "DELETE FROM {tripal_gffprotein_temp}";
  543. chado_query($sql);
  544. }
  545. /**
  546. * Makes sure Chado is ready with the necessary synonym type records.
  547. */
  548. private function prepSynonms() {
  549. // make sure we have a 'synonym_type' vocabulary
  550. $select = ['name' => 'synonym_type'];
  551. $results = chado_select_record('cv', ['*'], $select);
  552. if (count($results) == 0) {
  553. // insert the 'synonym_type' vocabulary
  554. $values = [
  555. 'name' => 'synonym_type',
  556. 'definition' => 'vocabulary for synonym types',
  557. ];
  558. $success = chado_insert_record('cv', $values, array(
  559. 'skip_validation' => TRUE,
  560. ));
  561. if (!$success) {
  562. $this->logMessage("Failed to add the synonyms type vocabulary.", [], TRIPAL_WARNING);
  563. return 0;
  564. }
  565. // now that we've added the cv we need to get the record
  566. $results = chado_select_record('cv', ['*'], $select);
  567. if (count($results) > 0) {
  568. $syncv = $results[0];
  569. }
  570. }
  571. else {
  572. $syncv = $results[0];
  573. }
  574. // get the 'exact' cvterm, which is the type of synonym we're adding
  575. $select = [
  576. 'name' => 'exact',
  577. 'cv_id' => [
  578. 'name' => 'synonym_type',
  579. ],
  580. ];
  581. $result = chado_select_record('cvterm', ['*'], $select);
  582. if (count($result) == 0) {
  583. $term = [
  584. 'name' => 'exact',
  585. 'id' => "synonym_type:exact",
  586. 'definition' => '',
  587. 'is_obsolete' => 0,
  588. 'cv_name' => $syncv->name,
  589. 'is_relationship' => FALSE,
  590. ];
  591. $syntype = chado_insert_cvterm($term, ['update_existing' => TRUE]);
  592. if (!$syntype) {
  593. $this->logMessage("Cannot add synonym type: internal:$type.", [], TRIPAL_WARNING);
  594. return 0;
  595. }
  596. }
  597. else {
  598. $syntype = $result[0];
  599. }
  600. $this->exact_syn = $syntype;
  601. }
  602. /**
  603. * Makes sure there is a null publication in the database.
  604. */
  605. private function prepNullPub(){
  606. // check to see if we have a NULL publication in the pub table. If not,
  607. // then add one.
  608. $select = ['uniquename' => 'null'];
  609. $result = chado_select_record('pub', ['*'], $select);
  610. if (count($result) == 0) {
  611. $pub_sql = "
  612. INSERT INTO {pub} (uniquename,type_id)
  613. VALUES (:uname,
  614. (SELECT cvterm_id
  615. FROM {cvterm} CVT
  616. INNER JOIN {dbxref} DBX ON DBX.dbxref_id = CVT.dbxref_id
  617. INNER JOIN {db} DB ON DB.db_id = DBX.db_id
  618. WHERE CVT.name = :type_id))
  619. ";
  620. $status = chado_query($psql);
  621. if (!$status) {
  622. $this->logMessage("Cannot prepare statement 'ins_pub_uniquename_typeid.", [], TRIPAL_WARNING);
  623. return 0;
  624. }
  625. // insert the null pub
  626. $result = chado_query($pub_sql, [
  627. ':uname' => 'null',
  628. ':type_id' => 'null',
  629. ])->fetchObject();
  630. if (!$result) {
  631. $this->logMessage("Cannot add null publication needed for setup of alias.", [], TRIPAL_WARNING);
  632. return 0;
  633. }
  634. $result = chado_select_record('pub', ['*'], $select);
  635. $pub = $result[0];
  636. }
  637. else {
  638. $pub = $result[0];
  639. }
  640. $this->null_pub = $pub;
  641. }
  642. /**
  643. * Parses the current line of the GFF3 file for a feature.
  644. *
  645. * @return array
  646. * An associative array containing the 9 elements othe GFF3 file. The
  647. * 9th element is an associative array of the attributes.
  648. */
  649. private function parseFeature($line) {
  650. $date = getdate();
  651. // get the columns
  652. $cols = explode("\t", $line);
  653. if (sizeof($cols) != 9) {
  654. throw new Exception(t('Improper number of columns on line %line_num: %line', ['%line_num' => $this->current_line, '%line' => $line]));
  655. }
  656. $ret = [
  657. 'line' => $this->current_line,
  658. 'landmark' => $cols[0],
  659. 'source' => $cols[1],
  660. 'type' => $cols[2],
  661. 'start' => $cols[3],
  662. 'end' => $cols[4],
  663. 'score' => $cols[5],
  664. 'strand' => $cols[6],
  665. 'phase' => $cols[7],
  666. 'attrs' => [],
  667. ];
  668. // Ready the start and stop for chado. Chado expects these positions
  669. // to be zero-based, so we substract 1 from the fmin. Also, in case
  670. // they are backwards, put them in the right order.
  671. $fmin = $ret['start'] - 1;
  672. $fmax = $ret['end'];
  673. if ($ret['end'] < $ret['start']) {
  674. $fmin = $ret['end'] - 1;
  675. $fmax = $ret['start'];
  676. }
  677. $ret['start'] = $fmin;
  678. $ret['stop'] = $fmax;
  679. // Format the strand for chado
  680. if (strcmp($ret['strand'], '.') == 0) {
  681. $ret['strand'] = 0;
  682. }
  683. elseif (strcmp($ret['strand'], '+') == 0) {
  684. $ret['strand'] = 1;
  685. }
  686. elseif (strcmp($ret['strand'], '-') == 0) {
  687. $ret['strand'] = -1;
  688. }
  689. if (strcmp($ret['phase'], '.') == 0) {
  690. if (strtolower($ret['type']) == 'cds') {
  691. $ret['phase'] = '0';
  692. }
  693. else {
  694. $ret['phase'] = '';
  695. }
  696. }
  697. $tags = [];
  698. $attr_name = '';
  699. $attr_uniquename = '';
  700. $attrs = explode(";", $cols[8]);
  701. $attr_organism = $this->organism;
  702. $attr_parent = '';
  703. $attr_others = [];
  704. $attr_aliases = [];
  705. foreach ($attrs as $attr) {
  706. $attr = rtrim($attr);
  707. $attr = ltrim($attr);
  708. if (strcmp($attr, '') == 0) {
  709. continue;
  710. }
  711. if (!preg_match('/^[^\=]+\=.+$/', $attr)) {
  712. throw new Exception(t('Attribute is not correctly formatted on line %line_num: %attr',
  713. ['%line_num' => $this->current_line, '%attr' => $attr]));
  714. }
  715. // Break apart each attribute into key/value pairs.
  716. $tag = preg_split("/=/", $attr, 2);
  717. // Multiple values of an attribute are separated by commas
  718. $tag_name = $tag[0];
  719. if (!array_key_exists($tag_name, $tags)) {
  720. $tags[$tag_name] = [];
  721. }
  722. $tags[$tag_name] = array_merge($tags[$tag_name], explode(",", $tag[1]));
  723. // Replace the URL escape codes for each tag
  724. for ($i = 0; $i < count($tags[$tag_name]); $i++) {
  725. $tags[$tag_name][$i] = urldecode($tags[$tag_name][$i]);
  726. }
  727. if (strcmp($tag_name, 'organism') == 0) {
  728. $attr_organism = $this->getOrganism(urldecode($tag[1]));
  729. }
  730. elseif (strcmp($tag_name, 'Alias') == 0) {
  731. $attr_aliases = array_merge($attr_aliases, $tags[$tag_name]);
  732. }
  733. elseif (strcmp($tag_name, 'Parent') == 0) {
  734. $attr_parent = urldecode($tag[1]);
  735. }
  736. // Get the list of non-reserved attributes.
  737. elseif (strcmp($tag_name, 'Name') !=0 and strcmp($tag_name, 'ID') !=0 and
  738. strcmp($tag_name, 'Alias') != 0 and strcmp($tag_name, 'Parent') != 0 and
  739. strcmp($tag_name, 'Target') != 0 and strcmp($tag_name, 'Gap') != 0 and
  740. strcmp($tag_name, 'Derives_from') != 0 and strcmp($tag_name, 'Note') != 0 and
  741. strcmp($tag_name, 'Dbxref') != 0 and strcmp($tag_name, 'Ontology_term') != 0 and
  742. strcmp($tag_name, 'Is_circular') != 0 and strcmp($tag_name, 'target_organism') != 0 and
  743. strcmp($tag_name, 'target_type') != 0 and strcmp($tag_name, 'organism' != 0)) {
  744. foreach ($tags[$tag_name] as $value) {
  745. if (!array_key_exists($tag_name, $attr_others)) {
  746. $attr_others[$tag_name] = [];
  747. }
  748. $attr_others[$tag_name][] = $value;
  749. }
  750. }
  751. }
  752. // Get the landmark feature.
  753. $landmark = $this->getLandmark($ret['landmark']);
  754. // If neither name nor uniquename are provided then generate one.
  755. $names = $this->getFeatureName($tags, $ret['type'], $ret['landmark'], $fmin, $fmax);
  756. $attr_uniquename = $names['uniquename'];
  757. $attr_name = $names['name'];
  758. $ret['name'] = $attr_name;
  759. $ret['uniquename'] = $attr_uniquename;
  760. $ret['synonyms'] = $attr_aliases;
  761. // Now add all of the attributes into the return array.
  762. foreach ($tags as $key => $value) {
  763. $ret['attrs'][$key] = $value;
  764. }
  765. $ret['organism_id'] = $attr_organism->getValue('organism_id');
  766. $ret['properties'] = $attr_others;
  767. if ($attr_parent) {
  768. $ret['Parent'] = $attr_parent;
  769. }
  770. return $ret;
  771. }
  772. /**
  773. * Indexes the FASTA section of the file for quick lookup.
  774. */
  775. private function indexFASTA() {
  776. // Iterate through the remaining lines of the file
  777. while ($line = fgets($this->gff_file_h)) {
  778. $this->current_line++;
  779. $this->addItemsHandled(drupal_strlen($line));
  780. // Get the ID and the current file pointer and store that for later.
  781. if (preg_match('/^>/', $line)) {
  782. $id = preg_replace('/^>([^\s]+).*$/', '\1', $line);
  783. $this->residue_index[$id] = ftell($this->gff_file_h);
  784. }
  785. }
  786. }
  787. /**
  788. * Loads into the database any landmark sequences.
  789. *
  790. * @param $line
  791. * The line from the GFF file that is the ##sequence-region comment.
  792. */
  793. private function loadLandmark($line) {
  794. $region_matches = [];
  795. if (preg_match('/^##sequence-region\s+(\w*?)\s+(\d+)\s+(\d+)$/i', $line, $region_matches)) {
  796. $rid = $region_matches[1];
  797. $landmark = $this->getLandmark($rid, NULL, TRUE);
  798. if (!$landmark) {
  799. $rstart = $region_matches[2];
  800. $rend = $region_matches[3];
  801. if (!$this->landmark_type) {
  802. 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.',
  803. ['!landmark' => $rid]));
  804. }
  805. $this->logMessage('Adding a new landmark feature: !landmark', ['!landmark' => $rid]);
  806. $landmark = $this->loadFeature($this->organism, $this->analysis, $this->landmark_cvterm, $rid,
  807. $rid, '', 'f', 'f', 1, 0);
  808. $this->landmark_lookup[$rid] = $landmark;
  809. }
  810. }
  811. }
  812. /**
  813. *
  814. */
  815. private function parseGFF3() {
  816. $filesize = filesize($this->gff_file);
  817. $this->setTotalItems($filesize);
  818. // Holds a unique list of cvterms for later lookup.
  819. $feature_cvterms = [];
  820. $featureprop_cvterms = [];
  821. while ($line = fgets($this->gff_file_h)) {
  822. $this->current_line++;
  823. $this->addItemsHandled(drupal_strlen($line));
  824. $line = trim($line);
  825. if ($this->current_line < $this->start_line) {
  826. continue;
  827. }
  828. // If we're in the FASTA file we're at the end of the features so return.
  829. if (preg_match('/^##FASTA/i', $line)) {
  830. $this->indexFASTA();
  831. continue;
  832. }
  833. // if at the ##sequence-region line handle it.
  834. if (preg_match('/^##sequence-region/i', $line)) {
  835. $this->loadLandmark($line);
  836. continue;
  837. }
  838. // skip comments
  839. if (preg_match('/^#/', $line)) {
  840. continue;
  841. }
  842. // skip empty lines
  843. if (preg_match('/^\s*$/', $line)) {
  844. continue;
  845. }
  846. // Store this feature in the global feature array.
  847. $gff_feature = $this->parseFeature($line);
  848. $this->features[$gff_feature['uniquename']] = $gff_feature;
  849. // Store any parent/child relationships
  850. if (array_key_exists('Parent', $gff_feature)) {
  851. // Add the parent relationship
  852. if (!array_key_exists($gff_feature['Parent'], $this->relationships['Parent'])) {
  853. $this->relationships['Parent'][$gff_feature['Parent']] = [];
  854. }
  855. if (!array_key_exists($gff_feature['type'], $this->relationships['Parent'][$gff_feature['Parent']])) {
  856. $this->relationships['Parent'][$gff_feature['Parent']][$gff_feature['type']] = [];
  857. }
  858. $this->relationships['Parent'][$gff_feature['Parent']][$gff_feature['type']][$gff_feature['start']] = $gff_feature['uniquename'];
  859. // Add the child relationship
  860. $this->relationships['Child'][$gff_feature['uniquename']] = $gff_feature['Parent'];
  861. }
  862. // Organize the CVterms for faster access later on.
  863. if (!array_key_exists($gff_feature['type'], $feature_cvterms)) {
  864. $feature_cvterms[$gff_feature['type']] = 0;
  865. }
  866. $feature_cvterms[$gff_feature['type']]++;
  867. // Organize the feature property types for faster access later on.
  868. foreach ($gff_feature['properties'] as $prop_name => $value) {
  869. if (!array_key_exists($prop_name, $featureprop_cvterms)) {
  870. $featureprop_cvterms[$prop_name] = 0;
  871. }
  872. $featureprop_cvterms[$prop_name]++;
  873. }
  874. }
  875. // Iterate through the feature type terms and get a chado object for each.
  876. $feature_cvterm_ids = [];
  877. foreach ($feature_cvterms as $name => $counts) {
  878. $cvterm = $this->getCvterm($name, $this->feature_cv->getValue('cv_id'));
  879. $this->feature_cvterm_lookup[$name] = $cvterm;
  880. $feature_cvterm_ids[] = $cvterm->cvterm_id;
  881. }
  882. // Iterate through the featureprop type terms and get a chado object for
  883. // each. If it doesn't exist then add one.
  884. foreach ($featureprop_cvterms as $name => $counts) {
  885. $cvterm = $this->getCvterm($name, $this->feature_cv->getValue('cv_id'));
  886. if ($cvterm) {
  887. $this->featureprop_cvterm_lookup[$name] = $cvterm;
  888. }
  889. else {
  890. $term = [
  891. 'id' => "local:$name",
  892. 'name' => $name,
  893. 'is_obsolete' => 0,
  894. 'cv_name' => 'feature_property',
  895. 'db_name' => 'local',
  896. 'is_relationship' => FALSE,
  897. ];
  898. $cvterm = (object) chado_insert_cvterm($term, ['update_existing' => FALSE]);
  899. if (!$cvterm) {
  900. $this->logMessage("Cannot add cvterm, $name.", [], TRIPAL_WARNING);
  901. return 0;
  902. }
  903. $this->featureprop_cvterm_lookup[$name] = $cvterm;
  904. }
  905. }
  906. // Now, get a list of features for this organism and the given types
  907. // we will use this list to do an "in-memory" lookup to make sure we
  908. // are not violating the unique contraint of the feature table
  909. // prior to inserting the features.
  910. $sql = "
  911. SELECT F.uniquename, CVT.name as type
  912. FROM {feature} F
  913. INNER JOIN {cvterm} CVT on F.type_id = CVT.cvterm_id
  914. WHERE organism_id = :organism_id and type_id IN (:types)
  915. ";
  916. $result = chado_query($sql, [
  917. ':organism_id' => $this->organism_id,
  918. ':types' => $feature_cvterm_ids,
  919. ]);
  920. while ($feature = $result->fetchObject()) {
  921. $this->feature_lookup[$feature->type][$feature->uniquename] = TRUE;
  922. }
  923. }
  924. /**
  925. * Imports the feature records into Chado.
  926. */
  927. private function loadFeatures() {
  928. $batch_size = 1000;
  929. $num_features = count(array_keys($this->features));
  930. $num_batches = (int) ($num_features / $batch_size) + 1;
  931. $this->setItemsHandled(0);
  932. $this->setTotalItems($num_batches);
  933. // Get the current max feature id prior to inserting the batch so
  934. // we can retrieve the feature_ids of what was inserted afterwards.
  935. $result = chado_query("SELECT max(feature_id) AS max_id FROM {feature}");
  936. $start_id = $result->fetchField();
  937. $init_sql = "
  938. INSERT INTO {feature}
  939. (uniquename, name, type_id, organism_id, residues, md5checksum,
  940. seqlen, is_analysis, is_obsolete)
  941. VALUES\n";
  942. $i = 0;
  943. $batch_num = 1;
  944. $sql = '';
  945. $args = [];
  946. foreach ($this->features as $uniquename => $feature) {
  947. // Only do an insert if this feature doesn't already exist in the databse.
  948. if (!(array_key_exists($feature['type'], $this->feature_lookup) and
  949. array_key_exists($feature['uniquename'], $this->feature_lookup[$feature['type']]))){
  950. $i++;
  951. $residues = $this->getResidues($feature, FALSE);
  952. $sql .= "(:uniquename_$i, :name_$i, :type_id_$i, :organism_id_$i, :residues_$i, " .
  953. " :md5checksum_$i, :seqlen_$i, FALSE, FALSE),\n";
  954. $args[":uniquename_$i"] = $feature['uniquename'];
  955. $args[":name_$i"] = $feature['name'];
  956. $args[":type_id_$i"] = $this->feature_cvterm_lookup[$feature['type']]->cvterm_id;
  957. $args[":organism_id_$i"] = $feature['organism_id'];
  958. $args[":residues_$i"] = $residues;
  959. $args[":md5checksum_$i"] = md5($residues);
  960. $args[":seqlen_$i"] = strlen($residues);
  961. // If we've reached the size of the batch then let's do the insert.
  962. if ($i == $batch_size) {
  963. // Insert the batch.
  964. $sql = rtrim($sql, ",\n");
  965. $sql = $init_sql . $sql;
  966. $last_id = chado_query($sql, $args, ['return' => Database::RETURN_INSERT_ID]);
  967. $this->setItemsHandled($batch_num);
  968. $batch_num++;
  969. // Get the feature Ids for the batch sequences
  970. $sql = "
  971. SELECT feature_id, uniquename
  972. FROM {feature} F
  973. WHERE feature_id > $start_id and feature_id <= $last_id
  974. ";
  975. $results = chado_query($sql);
  976. while ($result = $results->fetcHobject()) {
  977. if (array_key_exists($result->uniquename, $this->features)) {
  978. $this->features[$result->uniquename]['feature_id'] = $result->feature_id;
  979. }
  980. }
  981. // Now reset all of the varables for the next batch.
  982. $sql = '';
  983. $i = 0;
  984. $args = [];
  985. $start_id = $last_id;
  986. }
  987. }
  988. }
  989. // Insert any remaining batch items
  990. if ($i > 0) {
  991. $sql = rtrim($sql, ",\n");
  992. $sql = $init_sql . $sql;
  993. $last_id = chado_query($sql, $args, ['return' => Database::RETURN_INSERT_ID]);
  994. $this->setItemsHandled($batch_num);
  995. // Get the feature Ids for the batch sequences
  996. $sql = "
  997. SELECT feature_id, uniquename
  998. FROM {feature} F
  999. WHERE feature_id > $start_id and feature_id <= $last_id
  1000. ";
  1001. $results = chado_query($sql);
  1002. while ($result = $results->fetcHobject()) {
  1003. if (array_key_exists($result->uniquename, $this->features)) {
  1004. $this->features[$result->uniquename]['feature_id'] = $result->feature_id;
  1005. }
  1006. }
  1007. }
  1008. }
  1009. /**
  1010. *
  1011. */
  1012. private function loadFeatureProps(){
  1013. $batch_size = 100;
  1014. $num_features = count(array_keys($this->features));
  1015. $num_batches = (int) ($num_features / $batch_size) + 1;
  1016. $this->setItemsHandled(0);
  1017. $this->setTotalItems($num_batches);
  1018. $init_sql = "
  1019. INSERT INTO {featureprop}
  1020. (feature_id, type_id, value, rank)
  1021. VALUES\n";
  1022. $i = 0;
  1023. $j = 0;
  1024. $batch_num = 1;
  1025. $sql = '';
  1026. $args = [];
  1027. foreach ($this->features as $uniquename => $feature) {
  1028. // Only do an insert if this feature doesn't already exist in the databse.
  1029. if (!(array_key_exists($feature['type'], $this->feature_lookup) and
  1030. array_key_exists($feature['uniquename'], $this->feature_lookup[$feature['type']]))) {
  1031. $i++;
  1032. // If this feature doesn't have a feature_id then someting is wrong.
  1033. if (!array_key_exists('feature_id', $feature)) {
  1034. throw new Exception(t('The feature, !feature, is in the GFF but somehow was not added to the database.',
  1035. ['!feature' => $uniquename . " (" . $feature['name'] . ") at line " . $feature['line'] . '.']));
  1036. }
  1037. // Iterate through all of the properties of this feature.
  1038. foreach ($feature['properties'] as $prop_name => $values) {
  1039. foreach ($values as $rank => $value) {
  1040. $j++;
  1041. $sql .= "(:feature_id_$j, :type_id_$j, :value_$j, :rank_$j),\n";
  1042. $args[":feature_id_$j"] = $feature['feature_id'];
  1043. $args[":type_id_$j"] = $this->featureprop_cvterm_lookup[$prop_name]->cvterm_id;
  1044. $args[":value_$j"] = $value;
  1045. $args[":rank_$j"] = $rank;
  1046. }
  1047. }
  1048. // If we've reached the size of the batch then let's do the insert.
  1049. if ($i == $batch_size) {
  1050. // Insert the batch.
  1051. $sql = rtrim($sql, ",\n");
  1052. $sql = $init_sql . $sql;
  1053. $last_id = chado_query($sql, $args, ['return' => Database::RETURN_INSERT_ID]);
  1054. $this->setItemsHandled($batch_num);
  1055. $batch_num++;
  1056. // Now reset all of the varables for the next batch.
  1057. $sql = '';
  1058. $i = 0;
  1059. $j = 0;
  1060. $args = [];
  1061. }
  1062. }
  1063. }
  1064. // Add any remaining batch items
  1065. if ($i > 0) {
  1066. $sql = rtrim($sql, ",\n");
  1067. $sql = $init_sql . $sql;
  1068. $last_id = chado_query($sql, $args, ['return' => Database::RETURN_INSERT_ID]);
  1069. $this->setItemsHandled($batch_num);
  1070. }
  1071. }
  1072. /**
  1073. *
  1074. */
  1075. private function loadFeatureLocs() {
  1076. $batch_size = 1000;
  1077. $num_features = count(array_keys($this->features));
  1078. $num_batches = (int) ($num_features / $batch_size) + 1;
  1079. $this->setItemsHandled(0);
  1080. $this->setTotalItems($num_batches);
  1081. $init_sql = "
  1082. INSERT INTO {featureloc}
  1083. (srcfeature_id, feature_id, fmin, fmax, strand, phase, rank)
  1084. VALUES\n";
  1085. $i = 0;
  1086. $batch_num = 1;
  1087. $sql = '';
  1088. $args = [];
  1089. foreach ($this->features as $uniquename => $feature) {
  1090. // Only do an insert if this feature doesn't already exist in the databse.
  1091. if (!(array_key_exists($feature['type'], $this->feature_lookup) and
  1092. array_key_exists($feature['uniquename'], $this->feature_lookup[$feature['type']]))) {
  1093. $i++;
  1094. // Skip any features that are landmarks. They are just redefining
  1095. // the landmark.
  1096. if (array_key_exists($feature['uniquename'], $this->landmark_lookup)) {
  1097. continue;
  1098. }
  1099. // If this feature doesn't have a feature_id then someting is wrong.
  1100. if (!array_key_exists('feature_id', $feature)) {
  1101. throw new Exception(t('The feature, !feature, is in the GFF but somehow was not added to the database.',
  1102. ['!feature' => $uniquename . " (" . $feature['name'] . ") at line " . $feature['line'] . '.']));
  1103. }
  1104. // Get the rank of this feature by ordering all of the other
  1105. // subfeatures of the same type that share the same parent.
  1106. // Order them by the fmin and use the index of this feature as the
  1107. // rank.
  1108. $rank = 0;
  1109. if (array_key_exists('Parent', $feature)) {
  1110. $coords = array_keys($this->relationships['Parent'][$feature['Parent']][$feature['type']]);
  1111. sort($coords);
  1112. $rank = array_search($feature['start'], $coords);
  1113. }
  1114. $sql .= "(:srcfeature_id_$i, :feature_id_$i, :fmin_$i, :fmax_$i," .
  1115. " :strand_$i, :phase_$i, :rank_$i),\n";
  1116. $args[":srcfeature_id_$i"] = $this->landmark_lookup[$feature['landmark']]->getValue('feature_id');
  1117. $args[":feature_id_$i"] = $feature['feature_id'];
  1118. $args[":fmin_$i"] = $feature['start'];
  1119. $args[":fmax_$i"] = $feature['end'];
  1120. $args[":strand_$i"] = $feature['strand'];
  1121. $args[":phase_$i"] = $feature['phase'] ? $feature['phase'] : NULL;
  1122. $args[":rank_$i"] = $rank;
  1123. // If we've reached the size of the batch then let's do the insert.
  1124. if ($i == $batch_size) {
  1125. // Insert the batch.
  1126. $sql = rtrim($sql, ",\n");
  1127. $sql = $init_sql . $sql;
  1128. //$last_id = chado_query($sql, $args, ['return' => Database::RETURN_INSERT_ID]);
  1129. $this->setItemsHandled($batch_num);
  1130. $batch_num++;
  1131. // Now reset all of the varables for the next batch.
  1132. $sql = '';
  1133. $i = 0;
  1134. $args = [];
  1135. }
  1136. }
  1137. }
  1138. // Add any remaining batch items
  1139. if ($i > 0) {
  1140. $sql = rtrim($sql, ",\n");
  1141. $sql = $init_sql . $sql;
  1142. $last_id = chado_query($sql, $args, ['return' => Database::RETURN_INSERT_ID]);
  1143. $this->setItemsHandled($batch_num);
  1144. }
  1145. }
  1146. /**
  1147. *
  1148. */
  1149. private function loadAliases(){
  1150. $batch_size = 1000;
  1151. $num_features = count(array_keys($this->features));
  1152. $num_batches = (int) ($num_features / $batch_size) + 1;
  1153. $this->setItemsHandled(0);
  1154. $this->setTotalItems($num_batches);
  1155. $init_syn_sql = "INSERT INTO {synonym} (name, type_id, synonym_sgml) VALUES \n";
  1156. $init_fsyn_sql = "INSERT INTO {feature_synonym} (synonym_id, feature_id, pub_id) VALUES \n";
  1157. $i = 0;
  1158. $batch_num = 1;
  1159. $syn_sql = '';
  1160. $syn_args = [];
  1161. $fsyn_sql = '';
  1162. $fsyn_args = [];
  1163. $batch_synonyms = [];
  1164. $batch_featuresyn = [];
  1165. foreach ($this->features as $uniquename => $feature) {
  1166. // Only do an insert if this feature doesn't already exist in the databse.
  1167. if (!(array_key_exists($feature['type'], $this->feature_lookup) and
  1168. array_key_exists($feature['uniquename'], $this->feature_lookup[$feature['type']]))) {
  1169. $i++;
  1170. // If this feature doesn't have a feature_id then someting is wrong.
  1171. if (!array_key_exists('feature_id', $feature)) {
  1172. throw new Exception(t('The feature, !feature, is in the GFF but somehow was not added to the database.',
  1173. ['!feature' => $uniquename . " (" . $feature['name'] . ") at line " . $feature['line'] . '.']));
  1174. }
  1175. // Get all of the synonyms for this batch.
  1176. foreach ($feature['synonyms'] as $index => $synonym) {
  1177. $batch_synonyms[] = $synonym;
  1178. $batch_featuresyn[] = [$synonym, $feature['feature_id']];
  1179. }
  1180. // If we've reached the size of the batch then let's do the insert.
  1181. if ($i == $batch_size) {
  1182. if (count($batch_synonyms) > 0) {
  1183. // First get the synonym_ids for those already in the database.
  1184. $syns_avail_sql = "SELECT synonym_id, name FROM {synonym} WHERE type_id = :type_id and name IN (:names)";
  1185. $syns_avail_args = [
  1186. ':type_id' => $this->exact_syn->cvterm_id,
  1187. ':names' => $batch_synonyms
  1188. ];
  1189. $syns_avail = chado_query($syns_avail_sql, $syns_avail_args)->fetchAllAssoc('name', PDO::FETCH_OBJ);
  1190. // First, add any missing synonyms
  1191. $j = 0;
  1192. foreach ($batch_synonyms as $index => $synonym) {
  1193. if (!array_key_exists($synonym, $syns_avail)) {
  1194. $j++;
  1195. $syn_sql .= "(:name_$j, :type_id_$j, ''),\n";
  1196. $syn_args[":name_$j"] = $synonym;
  1197. $syn_args[":type_id_$j"] = $this->exact_syn->cvterm_id;
  1198. }
  1199. }
  1200. if ($syn_sql) {
  1201. $syn_sql = rtrim($syn_sql, ",\n");
  1202. $syn_sql = $init_syn_sql . $syn_sql;
  1203. $last_id = chado_query($syn_sql, $syn_args, ['return' => Database::RETURN_INSERT_ID]);
  1204. $syns_avail = chado_query($syns_avail_sql, $syns_avail_args)->fetchAllAssoc('name', PDO::FETCH_OBJ);
  1205. }
  1206. // Add in the feature synonym records for this batch.
  1207. $j = 0;
  1208. foreach ($batch_featuresyn as $index => $featuresyn) {
  1209. $j++;
  1210. $fsyn_sql .= "(:synonym_id_$j, :feature_id_$j, :pub_id_$j),\n";
  1211. $fsyn_args[":synonym_id_$j"] = $syns_avail[$featuresyn[0]]->synonym_id;
  1212. $fsyn_args[":feature_id_$j"] = $featuresyn[1];
  1213. $fsyn_args[":pub_id_$j"] = $this->null_pub->pub_id;
  1214. }
  1215. $fsyn_sql = rtrim($fsyn_sql, ",\n");
  1216. $fsyn_sql = $init_fsyn_sql . $fsyn_sql;
  1217. $last_id = chado_query($fsyn_sql, $fsyn_args, ['return' => Database::RETURN_INSERT_ID]);
  1218. }
  1219. $this->setItemsHandled($batch_num);
  1220. // Now reset all of the varables for the next batch.
  1221. $syn_sql = '';
  1222. $fsyn_sql = '';
  1223. $i = 0;
  1224. $syn_args = [];
  1225. $fsyn_args = [];
  1226. $batch_synonyms = [];
  1227. $batch_featuresyn = [];
  1228. }
  1229. }
  1230. }
  1231. // Add any remaining batch items
  1232. if ($i > 0) {
  1233. if (count($batch_synonyms) > 0) {
  1234. // First get the synonym_ids for those already in the database.
  1235. $syns_avail_sql = "SELECT synonym_id, name FROM {synonym} WHERE type_id = :type_id and name IN (:names)";
  1236. $syns_avail_args = [
  1237. ':type_id' => $this->exact_syn->cvterm_id,
  1238. ':names' => $batch_synonyms
  1239. ];
  1240. $syns_avail = chado_query($syns_avail_sql, $syns_avail_args)->fetchAllAssoc('name', PDO::FETCH_OBJ);
  1241. // First, add any missing synonyms
  1242. $j = 0;
  1243. foreach ($batch_synonyms as $index => $synonym) {
  1244. if (!array_key_exists($synonym, $syns_avail)) {
  1245. $j++;
  1246. $syn_sql .= "(:name_$j, :type_id_$j, ''),\n";
  1247. $syn_args[":name_$j"] = $synonym;
  1248. $syn_args[":type_id_$j"] = $this->exact_syn->cvterm_id;
  1249. }
  1250. }
  1251. if ($syn_sql) {
  1252. $syn_sql = rtrim($syn_sql, ",\n");
  1253. $syn_sql = $init_syn_sql . $syn_sql;
  1254. $last_id = chado_query($syn_sql, $syn_args, ['return' => Database::RETURN_INSERT_ID]);
  1255. $syns_avail = chado_query($syns_avail_sql, $syns_avail_args)->fetchAllAssoc('name', PDO::FETCH_OBJ);
  1256. }
  1257. // Add in the feature synonym records for this batch.
  1258. $j = 0;
  1259. foreach ($batch_featuresyn as $index => $featuresyn) {
  1260. $j++;
  1261. $fsyn_sql .= "(:synonym_id_$j, :feature_id_$j, :pub_id_$j),\n";
  1262. $fsyn_args[":synonym_id_$j"] = $syns_avail[$featuresyn[0]]->synonym_id;
  1263. $fsyn_args[":feature_id_$j"] = $featuresyn[1];
  1264. $fsyn_args[":pub_id_$j"] = $this->null_pub->pub_id;
  1265. }
  1266. $fsyn_sql = rtrim($fsyn_sql, ",\n");
  1267. $fsyn_sql = $init_fsyn_sql . $fsyn_sql;
  1268. $last_id = chado_query($fsyn_sql, $fsyn_args, ['return' => Database::RETURN_INSERT_ID]);
  1269. }
  1270. $this->setItemsHandled($batch_num);
  1271. }
  1272. }
  1273. /**
  1274. * Load a GFF3 file. This is the function called by tripal jobs
  1275. *
  1276. * @ingroup gff3_loader
  1277. */
  1278. private function loadGFF3() {
  1279. $ret = [];
  1280. $date = getdate();
  1281. $filesize = filesize($this->gff_file);
  1282. $this->setTotalItems($filesize);
  1283. $in_fasta = 0;
  1284. $line_num = 0;
  1285. $num_read = 0;
  1286. // iterate through each line of the GFF file
  1287. while ($line = fgets($this->gff_file_h)) {
  1288. $line_num++;
  1289. $this->line_num = $line_num;
  1290. $size = drupal_strlen($line);
  1291. $this->addItemsHandled($size);
  1292. $num_read += $size;
  1293. if ($line_num < $this->start_line) {
  1294. continue;
  1295. }
  1296. // check to see if we have FASTA section, if so then set the variable
  1297. // to start parsing
  1298. if (preg_match('/^##FASTA/i', $line)) {
  1299. $this->logMessage("Parsing FASTA portion...");
  1300. if ($remove) {
  1301. // we're done because this is a delete operation so break out of the loop.
  1302. break;
  1303. }
  1304. $this->loadFasta($fh, $interval, $num_read, $line_num, $filesize);
  1305. continue;
  1306. }
  1307. // if the ##sequence-region line is present then we want to add a new feature
  1308. if (preg_match('/^##sequence-region\s+(\w*?)\s+(\d+)\s+(\d+)$/i', $line, $region_matches)) {
  1309. $rid = $region_matches[1];
  1310. $rstart = $region_matches[2];
  1311. $rend = $region_matches[3];
  1312. if ($landmark_type) {
  1313. $this->loadFeature($organism, $analysis_id, $landmark_cvterm, $rid,
  1314. $rid, '', 'f', 'f', 1, 0);
  1315. }
  1316. continue;
  1317. }
  1318. // skip comments
  1319. if (preg_match('/^#/', $line)) {
  1320. continue;
  1321. }
  1322. // skip empty lines
  1323. if (preg_match('/^\s*$/', $line)) {
  1324. continue;
  1325. }
  1326. // get the columns
  1327. $cols = explode("\t", $line);
  1328. if (sizeof($cols) != 9) {
  1329. throw new Exception(t('Improper number of columns on line %line_num', ['%line_num' => $line_num]));
  1330. }
  1331. // get the column values
  1332. $landmark = $cols[0];
  1333. $source = $cols[1];
  1334. $type = $cols[2];
  1335. $start = $cols[3];
  1336. $end = $cols[4];
  1337. $score = $cols[5];
  1338. $strand = $cols[6];
  1339. $phase = $cols[7];
  1340. $attrs = explode(";", $cols[8]); // split by a semicolon
  1341. // ready the start and stop for chado. Chado expects these positions
  1342. // to be zero-based, so we substract 1 from the fmin
  1343. $fmin = $start - 1;
  1344. $fmax = $end;
  1345. if ($end < $start) {
  1346. $fmin = $end - 1;
  1347. $fmax = $start;
  1348. }
  1349. // format the strand for chado
  1350. if (strcmp($strand, '.') == 0) {
  1351. $strand = 0;
  1352. }
  1353. elseif (strcmp($strand, '+') == 0) {
  1354. $strand = 1;
  1355. }
  1356. elseif (strcmp($strand, '-') == 0) {
  1357. $strand = -1;
  1358. }
  1359. if (strcmp($phase, '.') == 0) {
  1360. if ($type == 'CDS') {
  1361. $phase = '0';
  1362. }
  1363. else {
  1364. $phase = '';
  1365. }
  1366. }
  1367. $cvterm = $this->getCvterm($type);
  1368. if (!$cvterm) {
  1369. throw new Exception(t('Cannot find feature term \'%type\' on line %line_num of the GFF file',
  1370. ['%type' => $type, '%line_num' => $line_num]));
  1371. }
  1372. // break apart each of the attributes
  1373. $tags = [];
  1374. $attr_name = '';
  1375. $attr_uniquename = '';
  1376. $attr_residue_info = '';
  1377. $attr_locgroup = 0;
  1378. $attr_fmin_partial = 'f';
  1379. $attr_fmax_partial = 'f';
  1380. $attr_is_obsolete = 'f';
  1381. $attr_is_analysis = 'f';
  1382. $attr_others = [];
  1383. $residues = '';
  1384. // the organism to which a feature belongs can be set in the GFF
  1385. // file using the 'organism' attribute. By default we
  1386. // set the $feature_organism variable to the default organism for the landmark
  1387. $attr_organism = '';
  1388. $feature_organism = $organism;
  1389. foreach ($attrs as $attr) {
  1390. $attr = rtrim($attr);
  1391. $attr = ltrim($attr);
  1392. if (strcmp($attr, '') == 0) {
  1393. continue;
  1394. }
  1395. if (!preg_match('/^[^\=]+\=.+$/', $attr)) {
  1396. throw new Exception(t('Attribute is not correctly formatted on line %line_num: %attr',
  1397. ['%line_num' => $line_num, '%attr' => $attr]));
  1398. }
  1399. // break apart each tag
  1400. $tag = preg_split("/=/", $attr, 2); // split by equals sign
  1401. // multiple instances of an attribute are separated by commas
  1402. $tag_name = $tag[0];
  1403. if (!array_key_exists($tag_name, $tags)) {
  1404. $tags[$tag_name] = [];
  1405. }
  1406. $tags[$tag_name] = array_merge($tags[$tag_name], explode(",", $tag[1])); // split by comma
  1407. // replace the URL escape codes for each tag
  1408. for ($i = 0; $i < count($tags[$tag_name]); $i++) {
  1409. $tags[$tag_name][$i] = urldecode($tags[$tag_name][$i]);
  1410. }
  1411. // get the name and ID tags
  1412. $skip_feature = 0; // if there is a problem with any of the attributes this variable gets set
  1413. if (strcmp($tag_name, 'ID') == 0) {
  1414. $attr_uniquename = urldecode($tag[1]);
  1415. }
  1416. elseif (strcmp($tag_name, 'Name') == 0) {
  1417. $attr_name = urldecode($tag[1]);
  1418. }
  1419. elseif (strcmp($tag_name, 'organism') == 0) {
  1420. $attr_organism = urldecode($tag[1]);
  1421. $org_matches = [];
  1422. if (preg_match('/^(.*?):(.*?)$/', $attr_organism, $org_matches)) {
  1423. $values = [
  1424. 'genus' => $org_matches[1],
  1425. 'species' => $org_matches[2],
  1426. ];
  1427. $org = chado_select_record('organism', ["*"], $values);
  1428. if (count($org) == 0) {
  1429. if ($create_organism) {
  1430. $feature_organism = (object) chado_insert_record('organism', $values, array(
  1431. 'skip_validation' => TRUE,
  1432. ));
  1433. if (!$feature_organism) {
  1434. $this->logMessage("Could not add the organism, '%org', from line %line. Skipping this line.",
  1435. [
  1436. '%org' => $attr_organism,
  1437. '%line' => $line_num,
  1438. ], TRIPAL_ERROR);
  1439. $skip_feature = 1;
  1440. }
  1441. }
  1442. else {
  1443. $this->logMessage("The organism attribute '%org' on line %line does not exist. Skipping this line.",
  1444. [
  1445. '%org' => $attr_organism,
  1446. '%line' => $line_num,
  1447. ], TRIPAL_ERROR);
  1448. $skip_feature = 1;
  1449. }
  1450. }
  1451. else {
  1452. // We found the organism in the database so use it.
  1453. $feature_organism = $org[0];
  1454. }
  1455. }
  1456. else {
  1457. $this->logMessage("The organism attribute '%org' on line %line is not properly formated. It " .
  1458. "should be of the form: organism=Genus:species. Skipping this line.",
  1459. ['%org' => $attr_organism, '%line' => $line_num], TRIPAL_ERROR);
  1460. $skip_feature = 1;
  1461. }
  1462. }
  1463. // Get the list of non-reserved attributes.
  1464. elseif (strcmp($tag_name, 'Alias') != 0 and strcmp($tag_name, 'Parent') != 0 and
  1465. strcmp($tag_name, 'Target') != 0 and strcmp($tag_name, 'Gap') != 0 and
  1466. strcmp($tag_name, 'Derives_from') != 0 and strcmp($tag_name, 'Note') != 0 and
  1467. strcmp($tag_name, 'Dbxref') != 0 and strcmp($tag_name, 'Ontology_term') != 0 and
  1468. strcmp($tag_name, 'Is_circular') != 0 and strcmp($tag_name, 'target_organism') != 0 and
  1469. strcmp($tag_name, 'target_type') != 0 and strcmp($tag_name, 'organism' != 0)) {
  1470. foreach ($tags[$tag_name] as $value) {
  1471. $attr_others[$tag_name][] = $value;
  1472. }
  1473. }
  1474. }
  1475. // If neither name nor uniquename are provided then generate one.
  1476. if (!$attr_uniquename and !$attr_name) {
  1477. // Check if an alternate ID field is suggested, if so, then use
  1478. // that for the name.
  1479. if (array_key_exists($alt_id_attr, $tags)) {
  1480. $attr_uniquename = $tags[$alt_id_attr][0];
  1481. $attr_name = $attr_uniquename;
  1482. }
  1483. // If the row has a parent then generate a uniquename using the parent name
  1484. // add the date to the name in the event there are more than one child with
  1485. // the same parent.
  1486. elseif (array_key_exists('Parent', $tags)) {
  1487. $attr_uniquename = $tags['Parent'][0] . "-$type-$landmark-" . $date[0] . ":" . ($fmin + 1) . ".." . $fmax;
  1488. $attr_name = $attr_uniquename;
  1489. }
  1490. // Generate a unique name based on the date, type and location
  1491. // and set the name to simply be the type.
  1492. else {
  1493. $attr_uniquename = $date[0] . "-$type-$landmark:" . ($fmin + 1) . ".." . $fmax;
  1494. $attr_name = $type;
  1495. }
  1496. }
  1497. // If a name is not specified then use the unique name as the name
  1498. if (strcmp($attr_name, '') == 0) {
  1499. $attr_name = $attr_uniquename;
  1500. }
  1501. // If an ID attribute is not specified then we must generate a
  1502. // unique ID. Do this by combining the attribute name with the date
  1503. // and line number.
  1504. if (!$attr_uniquename) {
  1505. $attr_uniquename = $attr_name . '-' . $date[0] . '-' . $line_num;
  1506. }
  1507. // Make sure the landmark sequence exists in the database. If the user
  1508. // has not specified a landmark type (and it's not required in the GFF
  1509. // format) then we don't know the type of the landmark so we'll hope
  1510. // that it's unique across all types for the organism. Only do this
  1511. // test if the landmark and the feature are different.
  1512. if (!$remove and !(strcmp($landmark, $attr_uniquename) == 0 or strcmp($landmark, $attr_name) == 0) and !in_array($landmark, $landmark_lookup)) {
  1513. $select = [
  1514. 'organism_id' => $organism->organism_id,
  1515. 'uniquename' => $landmark,
  1516. ];
  1517. $columns = ['count(*) as num_landmarks'];
  1518. if ($landmark_type) {
  1519. $select['type_id'] = [
  1520. 'name' => $landmark_type,
  1521. ];
  1522. }
  1523. $count = chado_select_record('feature', $columns, $select);
  1524. if (!$count or count($count) == 0 or $count[0]->num_landmarks == 0) {
  1525. // now look for the landmark using the name rather than uniquename.
  1526. $select = [
  1527. 'organism_id' => $organism->organism_id,
  1528. 'name' => $landmark,
  1529. ];
  1530. $columns = ['count(*) as num_landmarks'];
  1531. if ($landmark_type) {
  1532. $select['type_id'] = [
  1533. 'name' => $landmark_type,
  1534. ];
  1535. }
  1536. $count = chado_select_record('feature', $columns, $select);
  1537. if (!$count or count($count) == 0 or $count[0]->num_landmarks == 0) {
  1538. throw new Exception(t("The landmark '%landmark' cannot be found for this organism (%species) " .
  1539. "Please add the landmark and then retry the import of this GFF3 " .
  1540. "file", [
  1541. '%landmark' => $landmark,
  1542. '%species' => $organism->genus . " " . $organism->species,
  1543. ]));
  1544. }
  1545. elseif ($count[0]->num_landmarks > 1) {
  1546. throw new Exception(t("The landmark '%landmark' has more than one entry for this organism (%species) " .
  1547. "Cannot continue", [
  1548. '%landmark' => $landmark,
  1549. '%species' => $organism->genus . " " . $organism->species,
  1550. ]));
  1551. }
  1552. }
  1553. if ($count[0]->num_landmarks > 1) {
  1554. throw new Exception(t("The landmark '%landmark' is not unique for this organism. " .
  1555. "The features cannot be associated", ['%landmark' => $landmark]));
  1556. }
  1557. // The landmark was found, remember it
  1558. $landmark_lookup[] = $landmark;
  1559. }
  1560. // Add or update the feature and all properties.
  1561. if ($update or $refresh or $add_only) {
  1562. // Add/update the feature.
  1563. $feature = $this->loadFeature($feature_organism, $analysis_id, $cvterm,
  1564. $attr_uniquename, $attr_name, $residues, $attr_is_analysis,
  1565. $attr_is_obsolete, $add_only, $score);
  1566. if ($feature) {
  1567. // Add a record for this feature to the tripal_gff_temp table for
  1568. // later lookup.
  1569. $values = [
  1570. 'feature_id' => $feature->getID(),
  1571. 'organism_id' => $feature->getValue('organism_id'),
  1572. 'type_name' => $type,
  1573. 'uniquename' => $feature->getValue('uniquename'),
  1574. ];
  1575. // make sure this record doesn't already exist in our temp table
  1576. $results = chado_select_record('tripal_gff_temp', ['*'], $values);
  1577. if (count($results) == 0) {
  1578. $result = chado_insert_record('tripal_gff_temp', $values);
  1579. if (!$result) {
  1580. throw new Exception(t("Cound not save record in temporary table, Cannot continue.", []));
  1581. }
  1582. }
  1583. // Add/update the featureloc if the landmark and the ID are not the
  1584. // same if they are the same then this entry in the GFF is probably
  1585. // a landmark identifier.
  1586. if (strcmp($landmark, $attr_uniquename) != 0) {
  1587. $this->loadFeatureLoc($feature, $organism,
  1588. $landmark, $fmin, $fmax, $strand, $phase, $attr_fmin_partial,
  1589. $attr_fmax_partial, $attr_residue_info, $attr_locgroup);
  1590. }
  1591. // Add any aliases for this feature.
  1592. if (array_key_exists('Alias', $tags)) {
  1593. $this->loadAlias($feature, $tags['Alias']);
  1594. }
  1595. // Add any dbxrefs for this feature.
  1596. if (array_key_exists('Dbxref', $tags)) {
  1597. $this->loadDbxref($feature, $tags['Dbxref']);
  1598. }
  1599. // Add any ontology terms for this feature.
  1600. if (array_key_exists('Ontology_term', $tags)) {
  1601. $this->loadOntology($feature, $tags['Ontology_term']);
  1602. }
  1603. // Add parent relationships.
  1604. if (array_key_exists('Parent', $tags)) {
  1605. $this->loadParents($feature, $cvterm, $tags['Parent'],
  1606. $feature_organism->organism_id, $strand, $phase, $fmin, $fmax);
  1607. }
  1608. // Add target relationships.
  1609. if (array_key_exists('Target', $tags)) {
  1610. $this->loadTarget($feature, $tags, $target_organism_id, $target_type, $create_target, $attr_locgroup);
  1611. }
  1612. // Add gap information. This goes in simply as a property.
  1613. if (array_key_exists('Gap', $tags)) {
  1614. foreach ($tags['Gap'] as $value) {
  1615. $this->loadProperty($feature, 'Gap', $value);
  1616. }
  1617. }
  1618. // Add notes. This goes in simply as a property.
  1619. if (array_key_exists('Note', $tags)) {
  1620. foreach ($tags['Note'] as $value) {
  1621. $this->loadProperty($feature, 'Note', $value);
  1622. }
  1623. }
  1624. // Add the Derives_from relationship (e.g. polycistronic genes).
  1625. if (array_key_exists('Derives_from', $tags)) {
  1626. $this->loadDerivesFrom($feature, $cvterm, $tags['Derives_from'][0],
  1627. $feature_organism, $fmin, $fmax);
  1628. }
  1629. // Add in the GFF3_source dbxref so that GBrowse can find the feature
  1630. // using the source column.
  1631. $source_ref = ['GFF_source:' . $source];
  1632. $this->loadDbxref($feature, $source_ref);
  1633. // Add any additional attributes.
  1634. if ($attr_others) {
  1635. foreach ($attr_others as $tag_name => $values) {
  1636. foreach ($values as $value) {
  1637. $this->loadProperty($feature, $tag_name, $value);
  1638. }
  1639. }
  1640. }
  1641. }
  1642. }
  1643. }
  1644. // Do some last bit of processing.
  1645. if (!$remove) {
  1646. // First, add any protein sequences if needed.
  1647. $sql = "SELECT feature_id FROM {tripal_gffcds_temp} LIMIT 1 OFFSET 1";
  1648. $has_cds = chado_query($sql)->fetchField();
  1649. if ($has_cds) {
  1650. $this->logMessage("\nAdding protein sequences if CDS exist and no proteins in GFF...");
  1651. $sql = "
  1652. SELECT F.feature_id, F.name, F.uniquename, TGCT.strand,
  1653. CVT.cvterm_id, CVT.name as feature_type,
  1654. min(TGCT.fmin) as fmin, max(TGCT.fmax) as fmax,
  1655. TGPT.feature_id as protein_id, TGPT.fmin as protein_fmin,
  1656. TGPT.fmax as protein_fmax, FLM.uniquename as landmark
  1657. FROM {tripal_gffcds_temp} TGCT
  1658. INNER JOIN {feature} F on F.feature_id = TGCT.parent_id
  1659. INNER JOIN {cvterm} CVT on CVT.cvterm_id = F.type_id
  1660. INNER JOIN {featureloc} L on F.feature_id = L.feature_id
  1661. INNER JOIN {feature} FLM on L.srcfeature_id = FLM.feature_id
  1662. LEFT JOIN {tripal_gffprotein_temp} TGPT on TGPT.parent_id = F.feature_id
  1663. GROUP BY F.feature_id, F.name, F.uniquename, CVT.cvterm_id, CVT.name,
  1664. TGPT.feature_id, TGPT.fmin, TGPT.fmax, TGCT.strand, FLM.uniquename
  1665. ";
  1666. $results = chado_query($sql);
  1667. $protein_cvterm = $this->getCvterm('polypeptide');
  1668. while ($result = $results->fetchObject()) {
  1669. // If a protein exists with this same parent then don't add a new
  1670. // protein.
  1671. if (!$result->protein_id) {
  1672. // Get details about this protein
  1673. if ($re_mrna and $re_protein) {
  1674. // We use a regex to generate protein name from mRNA name
  1675. $uname = preg_replace("/$re_mrna/", $re_protein, $result->uniquename);
  1676. $name = $result->name;
  1677. }
  1678. else {
  1679. // No regex, use the default '-protein' suffix
  1680. $uname = $result->uniquename . '-protein';
  1681. $name = $result->name;
  1682. }
  1683. $values = [
  1684. 'parent_id' => $result->feature_id,
  1685. 'fmin' => $result->fmin,
  1686. ];
  1687. $min_phase = chado_select_record('tripal_gffcds_temp', ['phase'], $values);
  1688. $values = [
  1689. 'parent_id' => $result->feature_id,
  1690. 'fmax' => $result->fmax,
  1691. ];
  1692. $max_phase = chado_select_record('tripal_gffcds_temp', ['phase'], $values);
  1693. $pfmin = $result->fmin;
  1694. $pfmax = $result->fmax;
  1695. if ($result->strand == '-1') {
  1696. $pfmax -= $max_phase[0]->phase;
  1697. }
  1698. else {
  1699. $pfmin += $min_phase[0]->phase;
  1700. }
  1701. if ($skip_protein == 0) {
  1702. // Add the new protein record.
  1703. $feature = $this->loadFeature($organism, $analysis_id,
  1704. $protein_cvterm, $uname, $name, '', 'f', 'f', 1, 0);
  1705. // Add the derives_from relationship.
  1706. $cvterm = $this->getCvterm($result->feature_type);
  1707. $this->loadDerivesFrom($feature, $cvterm,
  1708. $result->uniquename, $organism, $pfmin, $pfmax);
  1709. // Add the featureloc record. Set the start of the protein to
  1710. // be the start of the coding sequence minus the phase.
  1711. $this->loadFeatureLoc($feature, $organism, $result->landmark,
  1712. $pfmin, $pfmax, $result->strand, '', 'f', 'f', '', 0);
  1713. }
  1714. }
  1715. }
  1716. }
  1717. $this->logMessage("Setting ranks of children...");
  1718. // Get features in a relationship that are also children of an alignment.
  1719. $sql = "
  1720. SELECT DISTINCT F.feature_id, F.organism_id, F.type_id,
  1721. F.uniquename, FL.strand
  1722. FROM {tripal_gff_temp} TGT
  1723. INNER JOIN {feature} F ON TGT.feature_id = F.feature_id
  1724. INNER JOIN {feature_relationship} FR ON FR.object_id = TGT.feature_id
  1725. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = FR.type_id
  1726. INNER JOIN {featureloc} FL ON FL.feature_id = F.feature_id
  1727. WHERE CVT.name = 'part_of'
  1728. ";
  1729. $parents = chado_query($sql);
  1730. // Build and prepare the SQL for selecting the children relationship.
  1731. $sel_gffchildren_sql = "
  1732. SELECT DISTINCT FR.feature_relationship_id, FL.fmin, FR.rank
  1733. FROM {feature_relationship} FR
  1734. INNER JOIN {featureloc} FL on FL.feature_id = FR.subject_id
  1735. INNER JOIN {cvterm} CVT on CVT.cvterm_id = FR.type_id
  1736. WHERE FR.object_id = :feature_id AND CVT.name = 'part_of'
  1737. ORDER BY FL.fmin ASC
  1738. ";
  1739. // Now set the rank of any parent/child relationships. The order is based
  1740. // on the fmin. The start rank is 1. This allows features with other
  1741. // relationships to be '0' (the default), and doesn't interfer with the
  1742. // ordering defined here.
  1743. $num_recs = $parents->rowCount();
  1744. $i = 1;
  1745. while ($parent = $parents->fetchObject()) {
  1746. // get the children
  1747. $result = chado_query($sel_gffchildren_sql, [':feature_id' => $parent->feature_id]);
  1748. // build an array of the children
  1749. $children = [];
  1750. while ($child = $result->fetchObject()) {
  1751. $children[] = $child;
  1752. }
  1753. // the children list comes sorted in ascending fmin
  1754. // but if the parent is on the reverse strand we need to
  1755. // reverse the order of the children.
  1756. if ($parent->strand == -1) {
  1757. arsort($children);
  1758. }
  1759. // first set the ranks to a negative number so that we don't
  1760. // get a duplicate error message when we try to change any of them
  1761. $rank = -1;
  1762. foreach ($children as $child) {
  1763. $match = ['feature_relationship_id' => $child->feature_relationship_id];
  1764. $values = ['rank' => $rank];
  1765. chado_update_record('feature_relationship', $match, $values);
  1766. $rank--;
  1767. }
  1768. // now set the rank correctly. The rank should start at 0.
  1769. $rank = 0;
  1770. foreach ($children as $child) {
  1771. $match = ['feature_relationship_id' => $child->feature_relationship_id];
  1772. $values = ['rank' => $rank];
  1773. chado_update_record('feature_relationship', $match, $values);
  1774. $rank++;
  1775. }
  1776. $i++;
  1777. }
  1778. }
  1779. return 1;
  1780. }
  1781. /**
  1782. * Load a controlled vocabulary term.
  1783. *
  1784. * This method first checks if the term has already been loaded in the
  1785. * feature_cvterm_lookup array, which helps a lot with performance.
  1786. *
  1787. * @param $type
  1788. * @param $cv_id
  1789. *
  1790. * @ingroup gff3_loader
  1791. */
  1792. private function getCvterm($type, $cv_id = NULL) {
  1793. if (!isset($cv_id)) {
  1794. $cv_id = $this->sequence_cv_id;
  1795. }
  1796. if (array_key_exists($type, $this->feature_cvterm_lookup)) {
  1797. return $this->feature_cvterm_lookup[$type];
  1798. }
  1799. else {
  1800. $sel_cvterm_sql = "
  1801. SELECT CVT.cvterm_id
  1802. FROM {cvterm} CVT
  1803. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  1804. WHERE CVT.cv_id = {$cv_id} and
  1805. (lower(CVT.name) = lower(:name) or lower(CVTS.synonym) = lower(:synonym))
  1806. ";
  1807. $result = chado_query($sel_cvterm_sql, [
  1808. ':name' => $type,
  1809. ':synonym' => $type,
  1810. ]);
  1811. $cvterm = $result->fetchObject() ?? NULL;
  1812. if ($cvterm) {
  1813. $cvterm = chado_get_cvterm(array('cvterm_id' => $cvterm->cvterm_id)) ?? NULL;
  1814. }
  1815. $this->feature_cvterm_lookup[$type] = $cvterm;
  1816. return $cvterm;
  1817. }
  1818. }
  1819. /**
  1820. * Retrieves a ChadoRecord object for the landmark feature.
  1821. *
  1822. * @param $landmark_name
  1823. * The name of the landmark to get
  1824. * @param $landmark_type
  1825. * A ChadoRecord object for the type of landmark.
  1826. * @param $skip_on_missing
  1827. * If the landmark cannot be found and this arugment is FALSE then
  1828. * an error will be thrown. If TRUE then no error is thrown.
  1829. *
  1830. * @return
  1831. * A feature ChadoRecord object or NULL if the landmark is missing and
  1832. * $skip_on_missing is TRUE.
  1833. */
  1834. private function getLandmark($landmark_name, $landmark_type = NULL, $skip_on_missing = FALSE) {
  1835. // Before performing a database query check to see if
  1836. // this landmark is already in our lookup list.
  1837. if (array_key_exists($landmark_name, $this->landmark_lookup)) {
  1838. return $this->landmark_lookup[$landmark_name];
  1839. }
  1840. $landmark = new ChadoRecord('feature');
  1841. $landmark->setValues([
  1842. 'organism_id' => $this->organism_id,
  1843. 'uniquename' => $landmark_name,
  1844. ]);
  1845. if ($landmark_type) {
  1846. $landmark->setValue('type_id', $landmark_type->getValue('cvterm_id'));
  1847. }
  1848. $num_found = $landmark->find();
  1849. if ($num_found == 0) {
  1850. if ($skip_on_missing == TRUE) {
  1851. return NULL;
  1852. }
  1853. throw new Exception(t("The landmark '%landmark' cannot be found for this organism (%species) " .
  1854. "Please add the landmark and then retry the import of this GFF3 " .
  1855. "file", [
  1856. '%landmark' => $landmark_name,
  1857. '%species' => $this->organism->getValues('genus') . " " . $this->organism->getValues('species'),
  1858. ]));
  1859. }
  1860. if ($num_found > 1) {
  1861. 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." .
  1862. "Cannot continue", [
  1863. '%landmark' => $landmark_name,
  1864. '%species' => $this->organism->getValues('genus') . " " . $this->organism->getValues('species'),
  1865. ]));
  1866. }
  1867. // The landmark was found, remember it
  1868. $this->landmark_lookup[] = $landmark;
  1869. return $landmark;
  1870. }
  1871. /**
  1872. * Retrives the organism ID that matches the provided string.
  1873. *
  1874. * The organism string is expected to be in the format genus:species
  1875. * or just the full name separated by spaces.
  1876. */
  1877. private function getOrganism($org_string) {
  1878. // Before performing a database query check to see if
  1879. // this organism is already in our lookup list.
  1880. if (array_key_exists($org_string, $this->organism_lookup)) {
  1881. return $this->organism_lookup[$org_string];
  1882. }
  1883. // See if the genus and species are spearated by a colon.
  1884. $org_matches = [];
  1885. if (preg_match('/^(.*?):(.*?)$/', $org_string, $org_matches)) {
  1886. $values = [
  1887. 'genus' => $org_matches[1],
  1888. 'species' => $org_matches[2],
  1889. ];
  1890. }
  1891. // See if the genus, species and infraspecific name are present.
  1892. elseif (preg_match('/^(.*?)\s+(.*?)\s+(.*)$/', $org_string, $org_matches)) {
  1893. $values = [
  1894. 'genus' => $org_matches[1],
  1895. 'species' => $org_matches[2],
  1896. 'infraspecific_name' => $org_matches[3],
  1897. ];
  1898. }
  1899. // See if just the genus ans species are present.
  1900. elseif (preg_match('/^(.*?)\s+(.*?)$/', $org_string, $org_matches)) {
  1901. $values = [
  1902. 'genus' => $org_matches[1],
  1903. 'species' => $org_matches[2],
  1904. ];
  1905. }
  1906. else {
  1907. throw new Exception(t("The specified organism, '%organism', is not provided in a compatible format. It must be 'genus:species', 'genus species' or 'genus species infraspecific name'.", ['%organism' => $org_string]));
  1908. }
  1909. // Get the organism record and add it to our lookup list for next time.
  1910. $organism = new ChadoRecord('organism');
  1911. $organism->setValues($values);
  1912. $num_found = $organism->find();
  1913. if ($num_found == 0) {
  1914. throw new Exception(t("Cannot find the specified organism, '%organism', for this GFF3 file.", ['%organism' => $org_string]));
  1915. }
  1916. $this->organism_lookup[$org_string] = $organism;
  1917. return $organism;
  1918. }
  1919. /**
  1920. * Retrieves the residues for a given feature.
  1921. *
  1922. */
  1923. private function getResidues($feature, $is_landmark = FALSE) {
  1924. return '';
  1925. }
  1926. /**
  1927. * Determines the name for a feature using the ID and name attributes.
  1928. *
  1929. * @param $feature_attrs
  1930. * The associative array of attributes for the feature.
  1931. *
  1932. * @param $type
  1933. * The type of feature.
  1934. *
  1935. * @return array
  1936. * An associative array with 'uniquename' and 'name' keys.
  1937. */
  1938. private function getFeatureName($attrs, $type, $landmark_name, $fmin, $fmax) {
  1939. // To ensure a name is unique we may need to use the date.
  1940. $uniquename = '';
  1941. $name = '';
  1942. // If there is no ID or name then try to create a name and ID.
  1943. if (!array_key_exists('ID', $attrs) and !array_key_exists('name', $attrs)) {
  1944. // Check if an alternate ID field is suggested, if so, then use
  1945. // that for the name.
  1946. if (array_key_exists($this->alt_id_attr, $attrs)) {
  1947. $uniquename = $attrs[$this->alt_id_attr][0];
  1948. $name = $uniquename;
  1949. }
  1950. // If the row has a parent then generate a unqiue ID
  1951. elseif (array_key_exists('Parent', $attrs)) {
  1952. $uniquename = md5($attrs['Parent'][0] . "-" . $type . "-" .
  1953. $landmark_name . ":" . ($fmin + 1) . ".." . $fmax);
  1954. $name = $attrs['Parent'][0] . "-" . $type;
  1955. }
  1956. // Generate a unique name based on the date, type and location
  1957. // and set the name to simply be the type.
  1958. else {
  1959. $uniquename = md5($type . "-" . $landmark_name . ":" . ($fmin + 1) . ".." . $fmax);
  1960. $name = $type . "-" . $landmark_name;
  1961. }
  1962. }
  1963. elseif (!array_key_exists('name', $attrs)) {
  1964. $uniquename = $attrs['ID'][0];
  1965. $name = $attrs['ID'][0];
  1966. }
  1967. elseif (!array_key_exists('ID', $attrs)) {
  1968. $uniquename = $attrs['name'][0];
  1969. $name = $attrs['name'][0];
  1970. }
  1971. else {
  1972. $uniquename = $attrs['ID'][0];
  1973. $name = $attrs['name'][0];
  1974. }
  1975. // Does this uniquename already exist? This can happen for subfeatures
  1976. // (e.g. CDS features) that have multiple components but are really
  1977. // all the same thing.
  1978. if (array_key_exists($uniquename, $this->features)) {
  1979. if (array_key_exists('Parent', $attrs)) {
  1980. // Iterate through the list of similar IDs and see how many we have
  1981. // then add a numeric suffix.
  1982. $i = 2;
  1983. while (array_key_exists($uniquename . "_" . $i, $this->features)) {
  1984. $i++;
  1985. }
  1986. $uniquename = $uniquename . "_" . $i;
  1987. }
  1988. else {
  1989. throw new Exception(t("A feature with the same ID exists multiple times: !uname", ['!uname' => $uniquename]));
  1990. }
  1991. }
  1992. return [
  1993. 'name' => $name,
  1994. 'uniquename' => $uniquename,
  1995. ];
  1996. }
  1997. /**
  1998. * Load the derives from attribute for a gff3 feature
  1999. *
  2000. * @param $feature
  2001. * @param $subject
  2002. * @param $organism
  2003. *
  2004. * @ingroup gff3_loader
  2005. */
  2006. private function loadDerivesFrom($feature, $cvterm, $object,
  2007. $organism, $fmin, $fmax) {
  2008. $type = $cvterm->name;
  2009. $derivesfrom_term = $this->getCvterm('derives_from');
  2010. // First look for the object feature in the temp table to get it's type.
  2011. $values = [
  2012. 'organism_id' => $organism->organism_id,
  2013. 'uniquename' => $object,
  2014. ];
  2015. $result = chado_select_record('tripal_gff_temp', ['type_name'], $values);
  2016. $type_id = NULL;
  2017. if (count($result) > 0) {
  2018. $type_id = $this->getCvterm($result[0]->type_name)->cvterm_id ?? NULL;
  2019. }
  2020. // If the object wasn't in the temp table then look for it in the
  2021. // feature table and get it's type.
  2022. if (!$type_id) {
  2023. $result = chado_select_record('feature', ['type_id'], $values);
  2024. if (count($result) > 1) {
  2025. $this->logMessage("Cannot find feature type for, '!subject' , in 'derives_from' relationship. Multiple matching features exist with this uniquename.",
  2026. ['!subject' => $object], TRIPAL_WARNING);
  2027. return;
  2028. }
  2029. else {
  2030. if (count($result) == 0) {
  2031. $this->logMessage("Cannot find feature type for, '!subject' , in 'derives_from' relationship.",
  2032. ['!subject' => $object], TRIPAL_WARNING);
  2033. return '';
  2034. }
  2035. else {
  2036. $type_id = $result->type_id;
  2037. }
  2038. }
  2039. }
  2040. // Get the object feature.
  2041. $match = [
  2042. 'organism_id' => $organism->organism_id,
  2043. 'uniquename' => $object,
  2044. 'type_id' => $type_id,
  2045. ];
  2046. $ofeature = chado_select_record('feature', ['feature_id'], $match);
  2047. if (count($ofeature) == 0) {
  2048. $this->logMessage("Could not add 'Derives_from' relationship " .
  2049. "for %uniquename and %subject. Subject feature, '%subject', " .
  2050. "cannot be found.", [
  2051. '%uniquename' => $feature->getValue('uniquename'),
  2052. '%subject' => $subject,
  2053. ], TRIPAL_ERROR);
  2054. return;
  2055. }
  2056. // If this feature is a protein then add it to the tripal_gffprotein_temp.
  2057. if ($type == 'protein' or $type == 'polypeptide') {
  2058. $values = [
  2059. 'feature_id' => $feature->getID(),
  2060. 'parent_id' => $ofeature[0]->feature_id,
  2061. 'fmin' => $fmin,
  2062. 'fmax' => $fmax,
  2063. ];
  2064. $result = chado_insert_record('tripal_gffprotein_temp', $values);
  2065. if (!$result) {
  2066. throw new Exception(t("Cound not save record in temporary protein table, Cannot continue.", []));
  2067. }
  2068. }
  2069. // Now check to see if the relationship already exists. If it does
  2070. // then just return.
  2071. $values = [
  2072. 'object_id' => $ofeature[0]->feature_id,
  2073. 'subject_id' => $feature->getID(),
  2074. 'type_id' => $derivesfrom_term->cvterm_id,
  2075. 'rank' => 0,
  2076. ];
  2077. $rel = chado_select_record('feature_relationship', ['*'], $values);
  2078. if (count($rel) > 0) {
  2079. return;
  2080. }
  2081. // finally insert the relationship if it doesn't exist
  2082. $ret = chado_insert_record('feature_relationship', $values, array(
  2083. 'skip_validation' => TRUE,
  2084. ));
  2085. if (!$ret) {
  2086. $this->logMessage("Could not add 'Derives_from' relationship for :uniquename and :subject.",
  2087. [
  2088. ':uniquename' => $feature->getValue('uniquename'),
  2089. ':subject' => $subject,
  2090. ], TRIPAL_WARNING);
  2091. }
  2092. }
  2093. /**
  2094. * Load the parents for a gff3 feature
  2095. *
  2096. * @param $feature
  2097. * @param $cvterm
  2098. * @param $parents
  2099. * @param $organism_id
  2100. * @param $fmin
  2101. *
  2102. * @ingroup gff3_loader
  2103. */
  2104. private function loadParents($feature, $cvterm, $parents,
  2105. $organism_id, $strand, $phase, $fmin, $fmax) {
  2106. $uname = $feature->getValue('uniquename');
  2107. $type = $cvterm->name;
  2108. $rel_type = 'part_of';
  2109. $relcvterm = $this->getCvterm($rel_type);
  2110. if (!$relcvterm) {
  2111. throw new Exception(t("Cannot find the term, 'part_of', from the sequence ontology. This term is used for associating parent and children features. Please check that the ontology is fully imported."));
  2112. }
  2113. // Iterate through the parents in the list.
  2114. foreach ($parents as $parent) {
  2115. // Get the parent cvterm.
  2116. $values = [
  2117. 'organism_id' => $organism_id,
  2118. 'uniquename' => $parent,
  2119. ];
  2120. $result = chado_select_record('tripal_gff_temp', ['type_name'], $values);
  2121. if (count($result) == 0) {
  2122. $this->logMessage("Cannot find parent: %parent.", ['%parent' => $parent], TRIPAL_WARNING);
  2123. return '';
  2124. }
  2125. $parent_type = $result[0]->type_name;
  2126. // try to find the parent
  2127. $parentcvterm = $this->getCvterm($parent_type);
  2128. $values = [
  2129. 'organism_id' => $organism_id,
  2130. 'uniquename' => $parent,
  2131. 'type_id' => $parentcvterm->cvterm_id,
  2132. ];
  2133. $result = chado_select_record('feature', ['feature_id'], $values);
  2134. $parent_feature = $result[0];
  2135. // if the parent exists then add the relationship otherwise print error and skip
  2136. if ($parent_feature) {
  2137. // check to see if the relationship already exists
  2138. $values = [
  2139. 'object_id' => $parent_feature->feature_id,
  2140. 'subject_id' => $feature->getID(),
  2141. 'type_id' => $relcvterm->cvterm_id,
  2142. ];
  2143. $rel = chado_select_record('feature_relationship', ['*'], $values);
  2144. if (count($rel) > 0) {
  2145. }
  2146. else {
  2147. // the relationship doesn't already exist, so add it.
  2148. $values = [
  2149. 'subject_id' => $feature->getID(),
  2150. 'object_id' => $parent_feature->feature_id,
  2151. 'type_id' => $relcvterm->cvterm_id,
  2152. ];
  2153. $result = chado_insert_record('feature_relationship', $values, array(
  2154. 'skip_validation' => TRUE,
  2155. ));
  2156. if (!$result) {
  2157. $this->logMessage("Failed to insert feature relationship '$uname' ($type) $rel_type '$parent' ($parent_type).",
  2158. [], TRIPAL_WARNING);
  2159. }
  2160. }
  2161. // If this feature is a CDS and now that we know the parent we can
  2162. // add it to the tripal_gffcds_temp table for later lookup.
  2163. if ($type == 'CDS') {
  2164. $values = [
  2165. 'feature_id' => $feature->getID(),
  2166. 'parent_id' => $parent_feature->feature_id,
  2167. 'fmin' => $fmin,
  2168. 'fmax' => $fmax,
  2169. 'strand' => $strand,
  2170. ];
  2171. if (isset($phase)) {
  2172. $values['phase'] = $phase;
  2173. }
  2174. $result = chado_insert_record('tripal_gffcds_temp', $values, array(
  2175. 'skip_validation' => TRUE,
  2176. ));
  2177. if (!$result) {
  2178. throw new Exception(t("Cound not save record in temporary CDS table, Cannot continue.", []));
  2179. exit;
  2180. }
  2181. }
  2182. }
  2183. else {
  2184. $this->logMessage("Cannot establish relationship '$uname' ($type) $rel_type '$parent' ($parent_type): Cannot find the parent.",
  2185. [], TRIPAL_WARNING);
  2186. }
  2187. }
  2188. }
  2189. /**
  2190. * Load the dbxref attribute for a feature
  2191. *
  2192. * @param $feature
  2193. * @param $dbxrefs
  2194. *
  2195. * @ingroup gff3_loader
  2196. */
  2197. private function loadDbxref($feature, $dbxrefs) {
  2198. // iterate through each of the dbxrefs
  2199. foreach ($dbxrefs as $dbxref) {
  2200. // get the database name from the reference. If it doesn't exist then create one.
  2201. $ref = explode(":", $dbxref);
  2202. $dbname = trim($ref[0]);
  2203. $accession = trim($ref[1]);
  2204. // first look for the database name if it doesn't exist then create one.
  2205. // first check for the fully qualified URI (e.g. DB:<dbname>. If that
  2206. // can't be found then look for the name as is. If it still can't be found
  2207. // the create the database
  2208. $values = ['name' => "DB:$dbname"];
  2209. $db = chado_select_record('db', ['db_id'], $values);
  2210. if (count($db) == 0) {
  2211. $values = ['name' => "$dbname"];
  2212. $db = chado_select_record('db', ['db_id'], $values);
  2213. }
  2214. if (count($db) == 0) {
  2215. $values = [
  2216. 'name' => $dbname,
  2217. 'description' => 'Added automatically by the GFF loader',
  2218. ];
  2219. $success = chado_insert_record('db', $values, array(
  2220. 'skip_validation' => TRUE,
  2221. ));
  2222. if ($success) {
  2223. $values = ['name' => "$dbname"];
  2224. $db = chado_select_record('db', ['db_id'], $values);
  2225. }
  2226. else {
  2227. $this->logMessage("Cannot find or add the database $dbname.", [], TRIPAL_WARNING);
  2228. return 0;
  2229. }
  2230. }
  2231. $db = $db[0];
  2232. // now check to see if the accession exists
  2233. $values = [
  2234. 'accession' => $accession,
  2235. 'db_id' => $db->db_id,
  2236. ];
  2237. $dbxref = chado_select_record('dbxref', ['dbxref_id'], $values);
  2238. // if the accession doesn't exist then we want to add it
  2239. if (sizeof($dbxref) == 0) {
  2240. $values = [
  2241. 'db_id' => $db->db_id,
  2242. 'accession' => $accession,
  2243. 'version' => '',
  2244. ];
  2245. $ret = chado_insert_record('dbxref', $values, array(
  2246. 'skip_validation' => TRUE,
  2247. ));
  2248. $values = [
  2249. 'accession' => $accession,
  2250. 'db_id' => $db->db_id,
  2251. ];
  2252. $dbxref = chado_select_record('dbxref', ['dbxref_id'], $values);
  2253. }
  2254. $dbxref = $dbxref[0];
  2255. // check to see if this feature dbxref already exists
  2256. $values = [
  2257. 'dbxref_id' => $dbxref->dbxref_id,
  2258. 'feature_id' => $feature->getID(),
  2259. ];
  2260. $fdbx = chado_select_record('feature_dbxref', ['feature_dbxref_id'], $values);
  2261. // now associate this feature with the database reference if it doesn't
  2262. // already exist
  2263. if (sizeof($fdbx) == 0) {
  2264. $values = [
  2265. 'dbxref_id' => $dbxref->dbxref_id,
  2266. 'feature_id' => $feature->getID(),
  2267. ];
  2268. $success = chado_insert_record('feature_dbxref', $values, array(
  2269. 'skip_validation' => TRUE,
  2270. ));
  2271. if (!$success) {
  2272. $this->logMessage("Failed to insert Dbxref: $dbname:$accession.", [], TRIPAL_WARNING);
  2273. return 0;
  2274. }
  2275. }
  2276. }
  2277. return 1;
  2278. }
  2279. /**
  2280. * Load the cvterms for a feature.
  2281. *
  2282. * Assumes there is a dbxref.accession matching a cvterm.name
  2283. *
  2284. * @param $feature
  2285. * @param $dbxrefs
  2286. *
  2287. * @ingroup gff3_loader
  2288. */
  2289. private function loadOntology($feature, $dbxrefs) {
  2290. // iterate through each of the dbxrefs
  2291. foreach ($dbxrefs as $dbxref) {
  2292. // get the database name from the reference. If it doesn't exist then create one.
  2293. $ref = explode(":", $dbxref);
  2294. $dbname = trim($ref[0]);
  2295. $accession = trim($ref[1]);
  2296. // first look for the database name
  2297. $db = chado_select_record('db', ['db_id'], ['name' => "DB:$dbname"]);
  2298. if (sizeof($db) == 0) {
  2299. // now look for the name without the 'DB:' prefix.
  2300. $db = chado_select_record('db', ['db_id'], ['name' => "$dbname"]);
  2301. if (sizeof($db) == 0) {
  2302. $this->logMessage("Database, $dbname, is not present. Cannot associate term: $dbname:$accession.", [], TRIPAL_WARNING);
  2303. continue;
  2304. }
  2305. }
  2306. $db = $db[0];
  2307. // now check to see if the accession exists
  2308. $dbxref = chado_select_record('dbxref', ['dbxref_id'],
  2309. ['accession' => $accession, 'db_id' => $db->db_id]);
  2310. if (sizeof($dbxref) == 0) {
  2311. $this->logMessage("Accession, $accession is missing for reference: $dbname:$accession.", [], TRIPAL_WARNING);
  2312. continue;
  2313. }
  2314. $dbxref = $dbxref[0];
  2315. // now check to see if the cvterm exists
  2316. $cvterm = chado_select_record('cvterm', ['cvterm_id'], [
  2317. 'dbxref_id' => $dbxref->dbxref_id,
  2318. ]);
  2319. // if it doesn't exist in the cvterm table, look for an alternate id
  2320. if (sizeof($cvterm) == 0) {
  2321. $cvterm = chado_select_record('cvterm_dbxref', ['cvterm_id'], [
  2322. 'dbxref_id' => $dbxref->dbxref_id,
  2323. ]);
  2324. if (sizeof($cvterm) == 0) {
  2325. $this->logMessage("CV Term is missing for reference: $dbname:$accession.", [], TRIPAL_WARNING);
  2326. continue;
  2327. }
  2328. }
  2329. $cvterm = $cvterm[0];
  2330. // check to see if this feature cvterm already exists
  2331. $fcvt = chado_select_record('feature_cvterm', ['feature_cvterm_id'],
  2332. [
  2333. 'cvterm_id' => $cvterm->cvterm_id,
  2334. 'feature_id' => $feature->getID(),
  2335. ]);
  2336. // now associate this feature with the cvterm if it doesn't already exist
  2337. if (sizeof($fcvt) == 0) {
  2338. $values = [
  2339. 'cvterm_id' => $cvterm->cvterm_id,
  2340. 'feature_id' => $feature->getID(),
  2341. 'pub_id' => [
  2342. 'uniquename' => 'null',
  2343. ],
  2344. ];
  2345. $success = chado_insert_record('feature_cvterm', $values, array(
  2346. 'skip_validation' => TRUE,
  2347. ));
  2348. if (!$success) {
  2349. $this->logMessage("Failed to insert ontology term: $dbname:$accession.", [], TRIPAL_WARNING);
  2350. continue;
  2351. }
  2352. }
  2353. }
  2354. }
  2355. /**
  2356. * Load any aliases for a feature
  2357. *
  2358. * @param $feature
  2359. * @param $aliases
  2360. *
  2361. * @ingroup gff3_loader
  2362. */
  2363. private function loadAlias($feature, $aliases) {
  2364. // make sure we have a 'synonym_type' vocabulary
  2365. $select = ['name' => 'synonym_type'];
  2366. $results = chado_select_record('cv', ['*'], $select);
  2367. if (count($results) == 0) {
  2368. // insert the 'synonym_type' vocabulary
  2369. $values = [
  2370. 'name' => 'synonym_type',
  2371. 'definition' => 'vocabulary for synonym types',
  2372. ];
  2373. $success = chado_insert_record('cv', $values, array(
  2374. 'skip_validation' => TRUE,
  2375. ));
  2376. if (!$success) {
  2377. $this->logMessage("Failed to add the synonyms type vocabulary.", [], TRIPAL_WARNING);
  2378. return 0;
  2379. }
  2380. // now that we've added the cv we need to get the record
  2381. $results = chado_select_record('cv', ['*'], $select);
  2382. if (count($results) > 0) {
  2383. $syncv = $results[0];
  2384. }
  2385. }
  2386. else {
  2387. $syncv = $results[0];
  2388. }
  2389. // get the 'exact' cvterm, which is the type of synonym we're adding
  2390. $select = [
  2391. 'name' => 'exact',
  2392. 'cv_id' => [
  2393. 'name' => 'synonym_type',
  2394. ],
  2395. ];
  2396. $result = chado_select_record('cvterm', ['*'], $select);
  2397. if (count($result) == 0) {
  2398. $term = [
  2399. 'name' => 'exact',
  2400. 'id' => "synonym_type:exact",
  2401. 'definition' => '',
  2402. 'is_obsolete' => 0,
  2403. 'cv_name' => $syncv->name,
  2404. 'is_relationship' => FALSE,
  2405. ];
  2406. $syntype = chado_insert_cvterm($term, ['update_existing' => TRUE]);
  2407. if (!$syntype) {
  2408. $this->logMessage("Cannot add synonym type: internal:$type.", [], TRIPAL_WARNING);
  2409. return 0;
  2410. }
  2411. }
  2412. else {
  2413. $syntype = $result[0];
  2414. }
  2415. // iterate through all of the aliases and add each one
  2416. foreach ($aliases as $alias) {
  2417. // check to see if the alias already exists in the synonym table
  2418. // if not, then add it
  2419. $select = [
  2420. 'name' => $alias,
  2421. 'type_id' => $syntype->cvterm_id,
  2422. ];
  2423. $result = chado_select_record('synonym', ['*'], $select);
  2424. if (count($result) == 0) {
  2425. $values = [
  2426. 'name' => $alias,
  2427. 'type_id' => $syntype->cvterm_id,
  2428. 'synonym_sgml' => '',
  2429. ];
  2430. $success = chado_insert_record('synonym', $values, array(
  2431. 'skip_validation' => TRUE,
  2432. ));
  2433. if (!$success) {
  2434. $this->logMessage("Cannot add alias $alias to synonym table.", [], TRIPAL_WARNING);
  2435. return 0;
  2436. }
  2437. $result = chado_select_record('synonym', ['*'], $select);
  2438. $synonym = $result[0];
  2439. }
  2440. else {
  2441. $synonym = $result[0];
  2442. }
  2443. // check to see if we have a NULL publication in the pub table. If not,
  2444. // then add one.
  2445. $select = ['uniquename' => 'null'];
  2446. $result = chado_select_record('pub', ['*'], $select);
  2447. if (count($result) == 0) {
  2448. $pub_sql = "
  2449. INSERT INTO {pub} (uniquename,type_id)
  2450. VALUES (:uname,
  2451. (SELECT cvterm_id
  2452. FROM {cvterm} CVT
  2453. INNER JOIN {dbxref} DBX ON DBX.dbxref_id = CVT.dbxref_id
  2454. INNER JOIN {db} DB ON DB.db_id = DBX.db_id
  2455. WHERE CVT.name = :type_id))
  2456. ";
  2457. $status = chado_query($psql);
  2458. if (!$status) {
  2459. $this->logMessage("Cannot prepare statement 'ins_pub_uniquename_typeid.", [], TRIPAL_WARNING);
  2460. return 0;
  2461. }
  2462. // insert the null pub
  2463. $result = chado_query($pub_sql, [
  2464. ':uname' => 'null',
  2465. ':type_id' => 'null',
  2466. ])->fetchObject();
  2467. if (!$result) {
  2468. $this->logMessage("Cannot add null publication needed for setup of alias.", [], TRIPAL_WARNING);
  2469. return 0;
  2470. }
  2471. $result = chado_select_record('pub', ['*'], $select);
  2472. $pub = $result[0];
  2473. }
  2474. else {
  2475. $pub = $result[0];
  2476. }
  2477. // check to see if the synonym exists in the feature_synonym table
  2478. // if not, then add it.
  2479. $values = [
  2480. 'synonym_id' => $synonym->synonym_id,
  2481. 'feature_id' => $feature->getID(),
  2482. 'pub_id' => $pub->pub_id,
  2483. ];
  2484. $columns = ['feature_synonym_id'];
  2485. $result = chado_select_record('feature_synonym', $columns, $values);
  2486. if (count($result) == 0) {
  2487. $values = [
  2488. 'synonym_id' => $synonym->synonym_id,
  2489. 'feature_id' => $feature->getID(),
  2490. 'pub_id' => $pub->pub_id,
  2491. ];
  2492. $success = chado_insert_record('feature_synonym', $values, array(
  2493. 'skip_validation' => TRUE,
  2494. ));
  2495. if (!$success) {
  2496. $this->logMessage("Cannot add alias $alias to feature synonym table.", [], TRIPAL_WARNING);
  2497. return 0;
  2498. }
  2499. }
  2500. }
  2501. return 1;
  2502. }
  2503. /**
  2504. * Create the feature record & link it to it's analysis
  2505. *
  2506. * @param $organism
  2507. * @param $analysis_id
  2508. * @param $cvterm
  2509. * @param $uniquename
  2510. * @param $name
  2511. * @param $residues
  2512. * @param $is_analysis
  2513. * @param $is_obsolete
  2514. * @param $add_only
  2515. * @param $score
  2516. *
  2517. * @ingroup gff3_loader
  2518. */
  2519. private function loadFeature($organism, $analysis, $cvterm, $uniquename,
  2520. $name, $residues, $is_analysis = 'f', $is_obsolete = 'f', $add_only, $score) {
  2521. if (strcmp($is_obsolete, 'f') == 0 or $is_obsolete == 0) {
  2522. $is_obsolete = 'FALSE';
  2523. }
  2524. if (strcmp($is_obsolete, 't') == 0 or $is_obsolete == 1) {
  2525. $is_obsolete = 'TRUE';
  2526. }
  2527. if (strcmp($is_analysis, 'f') == 0 or $is_analysis == 0) {
  2528. $is_analysis = 'FALSE';
  2529. }
  2530. if (strcmp($is_analysis, 't') == 0 or $is_analysis == 1) {
  2531. $is_analysis = 'TRUE';
  2532. }
  2533. // Check to see if the feature already exists.
  2534. $feature = new ChadoRecord('feature');
  2535. $feature->setValues([
  2536. 'organism_id' => $organism->getValue('organism_id'),
  2537. 'uniquename' => $uniquename,
  2538. 'type_id' => $cvterm->getValue('cvterm_id'),
  2539. ]);
  2540. $num_matches = $feature->find();
  2541. // Insert the feature if it does not exist otherwise perform an update.
  2542. if ($num_matches == 0) {
  2543. $feature->setValue('name', $name);
  2544. $feature->setValue('md5checksum', md5($residues));
  2545. $feature->setValue('is_analysis', $is_analysis);
  2546. $feature->setValue('is_obsolete', $is_obsolete);
  2547. try {
  2548. $feature->insert();
  2549. }
  2550. catch (Exception $e) {
  2551. $this->logMessage("Failed to insert feature '$uniquename' (" . $cvterm->getValue('name') . ").", [], TRIPAL_WARNING);
  2552. return 0;
  2553. }
  2554. }
  2555. elseif (!$add_only) {
  2556. if ($num_matches > 1) {
  2557. $this->logMessage("Failed to update feature '$uniquename' (" . $cvterm->getValue('name') . "). More than one feature exists with these criteria", [], TRIPAL_WARNING);
  2558. return 0;
  2559. }
  2560. $feature->setValue('name', $name);
  2561. $feature->setValue('md5checksum', md5($residues));
  2562. $feature->setValue('is_analysis', $is_analysis);
  2563. $feature->setValue('is_obsolete', $is_obsolete);
  2564. try {
  2565. $feature->update();
  2566. }
  2567. catch (Exception $e) {
  2568. $this->logMessage("Failed to update feature '$uniquename' (" . $cvterm->getValue('name') . ").", [], TRIPAL_WARNING);
  2569. return 0;
  2570. }
  2571. }
  2572. else {
  2573. // The feature exists and we don't want to update it so return
  2574. // a value of 0. This will stop all downstream property additions
  2575. return $feature;
  2576. }
  2577. // Add the analysisfeature entry to the analysisfeature table if
  2578. // it doesn't already exist.
  2579. $af = new ChadoRecord('analysisfeature');
  2580. $af->setValues([
  2581. 'analysis_id' => $analysis->getValue('analysis_id'),
  2582. 'feature_id' => $feature->getID(),
  2583. ]);
  2584. $num_afs = $af->find();
  2585. if ($num_afs == 0) {
  2586. // if a score is available then set that to be the significance field
  2587. if (strcmp($score, '.') != 0) {
  2588. $af->setValue('significance', $score);
  2589. }
  2590. try {
  2591. $af->insert();
  2592. }
  2593. catch (Exception $e) {
  2594. $this->logMessage("Could not add analysisfeature record: " . $analysis->getValue('analysis_id') . ", " . $feature->getID() . ". " . $e->getMessage(), [], TRIPAL_WARNING);
  2595. }
  2596. }
  2597. else {
  2598. // if a score is available then set that to be the significance field
  2599. $new_vals = [];
  2600. if (strcmp($score, '.') != 0) {
  2601. $af->setValue('significance', $score);
  2602. }
  2603. else {
  2604. $af->setValue('significance', '__NULL__');
  2605. }
  2606. if (!$add_only) {
  2607. try {
  2608. $af->update();
  2609. }
  2610. catch (Exception $e) {
  2611. $this->logMessage("Could not update analysisfeature record: $analysis_id, " . $feature->getID() . ". " . $e->getMessage(), [], TRIPAL_WARNING);
  2612. }
  2613. }
  2614. }
  2615. return $feature;
  2616. }
  2617. /**
  2618. * Insert the location of the feature
  2619. *
  2620. * @param $feature
  2621. * @param $organism
  2622. * @param $landmark
  2623. * @param $fmin
  2624. * @param $fmax
  2625. * @param $strand
  2626. * @param $phase
  2627. * @param $is_fmin_partial
  2628. * @param $is_fmax_partial
  2629. * @param $residue_info
  2630. * @param $locgroup
  2631. * @param $landmark_type_id
  2632. * @param $landmark_organism_id
  2633. * @param $create_landmark
  2634. * @param $landmark_is_target
  2635. *
  2636. * @ingroup gff3_loader
  2637. */
  2638. private function loadFeatureLoc($feature, $organism, $landmark, $fmin,
  2639. $fmax, $strand, $phase, $is_fmin_partial, $is_fmax_partial, $residue_info, $locgroup,
  2640. $landmark_type_id = '', $landmark_organism_id = '', $create_landmark = 0,
  2641. $landmark_is_target = 0) {
  2642. $srcfeature = new ChadoRecord('feature');
  2643. $srcfeature->setValues([
  2644. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  2645. 'uniquename' => $landmark,
  2646. ]);
  2647. if ($landmark_type_id) {
  2648. $srcfeature->setValue('type_id', $landmark_type_id);
  2649. }
  2650. $num_srcf = $srcfeature->find();
  2651. if ($num_srcf == 0) {
  2652. // so we couldn't find the landmark using the uniquename. Let's try the 'name'.
  2653. // if we return only a single result then we can proceed. Otherwise give an
  2654. $srcfeature = new ChadoRecord('feature');
  2655. $srcfeature->setValues([
  2656. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  2657. 'name' => $landmark,
  2658. ]);
  2659. if ($landmark_type_id) {
  2660. $srcfeature->setValue('type_id', $landmark_type_id);
  2661. }
  2662. $num_srcf = $srcfeature->find();
  2663. if ($num_srcf == 0) {
  2664. // if the landmark is the target feature in a matched alignment then try one more time to
  2665. // find it by querying any feature with the same uniquename. If we find one then use it.
  2666. if ($landmark_is_target) {
  2667. $srcfeature = new ChadoRecord('feature');
  2668. $srcfeature->setValues([
  2669. 'uniquename' => $landmark,
  2670. ]);
  2671. $num_srcf = $srcfeature->find();
  2672. if ($num_srcf > 1) {
  2673. $this->logMessage("Multiple landmarks exist for a matached target with the name: '%landmark'. Cannot " .
  2674. "resolve which one to use. Cannot add the feature location record.",
  2675. ['%landmark' => $landmark], TRIPAL_WARNING);
  2676. }
  2677. }
  2678. if ($num_srcf == 0) {
  2679. // we couldn't find the landmark feature, so if the user has requested we create it then do so
  2680. // but only if we have a type id
  2681. if ($create_landmark and $landmark_type_id) {
  2682. $srcfeature = new ChadoRecord('feature');
  2683. $srcfeature->setValues([
  2684. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  2685. 'name' => $landmark,
  2686. 'uniquename' => $landmark,
  2687. 'type_id' => $landmark_type_id,
  2688. ]);
  2689. try {
  2690. $srcfeature->insert();
  2691. }
  2692. catch (Exception $e) {
  2693. $this->logMessage("Cannot find landmark feature: '%landmark', nor could it be inserted. " . $e->getMessage() ,
  2694. ['%landmark' => $landmark], TRIPAL_WARNING);
  2695. return 0;
  2696. }
  2697. }
  2698. else {
  2699. $this->logMessage("Cannot find unique landmark feature: '%landmark'.",
  2700. ['%landmark' => $landmark], TRIPAL_WARNING);
  2701. return 0;
  2702. }
  2703. }
  2704. }
  2705. elseif ($num_srcf > 1) {
  2706. $this->logMessage("multiple landmarks exist with the name: '%landmark'. Cannot " .
  2707. "resolve which one to use. Cannot add the feature location record.",
  2708. ['%landmark' => $landmark], TRIPAL_WARNING);
  2709. return 0;
  2710. }
  2711. }
  2712. elseif ($num_srcf > 1) {
  2713. $this->logMessage("multiple landmarks exist with the name: '%landmark'. Cannot " .
  2714. "resolve which one to use. Cannot add the feature location record.",
  2715. ['%landmark' => $landmark, TRIPAL_WARNING]);
  2716. return 0;
  2717. }
  2718. // TODO: create an attribute that recognizes the residue_info,locgroup,
  2719. // is_fmin_partial and is_fmax_partial, right now these are
  2720. // hardcoded to be false and 0 below.
  2721. // check to see if this featureloc already exists, but also keep track of the
  2722. // last rank value
  2723. $rank = 0;
  2724. $exists = 0;
  2725. $select = ['feature_id' => $feature->getID()];
  2726. $options = [
  2727. 'order_by' => [
  2728. 'rank' => 'ASC',
  2729. ],
  2730. ];
  2731. $locrecs = chado_select_record('featureloc', ['*'], $select, $options);
  2732. foreach ($locrecs as $locrec) {
  2733. // it is possible for the featureloc->srcfeature_id to be NULL.
  2734. // This can happen if the srcfeature is not known (according to chado
  2735. // table field descriptions). If it's null then just skip this entry.
  2736. if (!$locrec->srcfeature_id) {
  2737. continue;
  2738. }
  2739. $select = ['feature_id' => $locrec->srcfeature_id];
  2740. $columns = ['feature_id', 'name'];
  2741. $locsfeature = chado_select_record('feature', $columns, $select);
  2742. // the source feature name and at least the fmin and fmax must be the same
  2743. // for an update of the featureloc, otherwise we'll insert a new record.
  2744. if (strcmp($locsfeature[0]->name, $landmark) == 0 and
  2745. ($locrec->fmin == $fmin or $locrec->fmax == $fmax)) {
  2746. $featureloc = new ChadoRecord('featureloc');
  2747. $featureloc->setValue('featureloc_id', $locrec->featureloc_id);
  2748. $values = [];
  2749. $exists = 1;
  2750. if ($featureloc->fmin != $fmin) {
  2751. $featureloc->setValue('fmin', $fmin);
  2752. }
  2753. if ($featureloc->fmax != $fmax) {
  2754. $featureloc->setValue('fmax', $fmax);
  2755. }
  2756. if ($featureloc->strand != $strand) {
  2757. $featureloc->setValue('strand', $strand);
  2758. }
  2759. if (count($featureloc->getValues()) > 0) {
  2760. $featureloc->update();
  2761. }
  2762. }
  2763. $rank = $locrec->rank + 1;
  2764. }
  2765. if (!$exists) {
  2766. // this feature location is new so add it
  2767. if (strcmp($is_fmin_partial, 'f') == 0 or !$is_fmin_partial) {
  2768. $is_fmin_partial = 'FALSE';
  2769. }
  2770. elseif (strcmp($is_fmin_partial, 't') == 0 or $is_fmin_partial == 1) {
  2771. $is_fmin_partial = 'TRUE';
  2772. }
  2773. if (strcmp($is_fmax_partial, 'f') == 0 or !$is_fmax_partial) {
  2774. $is_fmax_partial = 'FALSE';
  2775. }
  2776. elseif (strcmp($is_fmax_partial, 't') == 0 or $is_fmax_partial == 1) {
  2777. $is_fmax_partial = 'TRUE';
  2778. }
  2779. $featureloc = new ChadoRecord('featureloc');
  2780. $featureloc->setValues([
  2781. 'feature_id' => $feature->getID(),
  2782. 'srcfeature_id' => $srcfeature->getID(),
  2783. 'fmin' => $fmin,
  2784. 'is_fmin_partial' => $is_fmin_partial,
  2785. 'fmax' => $fmax,
  2786. 'is_fmax_partial' => $is_fmax_partial,
  2787. 'strand' => $strand,
  2788. 'residue_info' => $residue_info,
  2789. 'locgroup' => $locgroup,
  2790. 'rank' => $rank,
  2791. ]);
  2792. if (!$residue_info) {
  2793. $featureloc->setValue('residue_info', '__NULL__');
  2794. }
  2795. if ($phase) {
  2796. $featureloc->setValue('phase', $phase);
  2797. }
  2798. $featureloc->insert();
  2799. }
  2800. return 1;
  2801. }
  2802. /**
  2803. * Load a preoprty (featurepop) for the feature
  2804. *
  2805. * @param $feature
  2806. * @param $property
  2807. * @param $value
  2808. *
  2809. * @ingroup gff3_loader
  2810. */
  2811. private function loadProperty($feature, $property, $value) {
  2812. // First make sure the cvterm exists. if not, then add it.
  2813. $result = $this->getCvterm($property, $this->feature_property_cv_id);
  2814. // If we don't have a property like this already, then add it otherwise,
  2815. // just return.
  2816. if (empty($result)) {
  2817. $term = [
  2818. 'id' => "local:$property",
  2819. 'name' => $property,
  2820. 'is_obsolete' => 0,
  2821. 'cv_name' => 'feature_property',
  2822. 'db_name' => 'local',
  2823. 'is_relationship' => FALSE,
  2824. ];
  2825. $cvterm = (object) chado_insert_cvterm($term, ['update_existing' => FALSE]);
  2826. if (!$cvterm) {
  2827. $this->logMessage("Cannot add cvterm, $property.", [], TRIPAL_WARNING);
  2828. return 0;
  2829. }
  2830. }
  2831. else {
  2832. $cvterm = $result;
  2833. }
  2834. // Check to see if the property already exists for this feature
  2835. // if it does but the value is unique then increment the rank and add it.
  2836. // if the value is not unique then don't add it.
  2837. $add = 1;
  2838. $rank = 0;
  2839. $select = [
  2840. 'feature_id' => $feature->getId(),
  2841. 'type_id' => $cvterm->cvterm_id,
  2842. ];
  2843. $options = [
  2844. 'order_by' => [
  2845. 'rank' => 'ASC',
  2846. ],
  2847. ];
  2848. $results = chado_select_record('featureprop', ['*'], $select, $options);
  2849. foreach ($results as $prop) {
  2850. if (strcmp($prop->value, $value) == 0) {
  2851. $add = NULL; // don't add it, it already exists
  2852. }
  2853. $rank = $prop->rank + 1;
  2854. }
  2855. // add the property if we pass the check above
  2856. if ($add) {
  2857. $values = [
  2858. 'feature_id' => $feature->getID(),
  2859. 'type_id' => $cvterm->cvterm_id,
  2860. 'value' => $value,
  2861. 'rank' => $rank,
  2862. ];
  2863. $result = chado_insert_record('featureprop', $values);
  2864. if (!$result) {
  2865. $this->logMessage("cannot add featureprop, $property.", [], TRIPAL_WARNING);
  2866. }
  2867. }
  2868. }
  2869. /**
  2870. * Load the FASTA sequences at the bottom of a GFF3 file
  2871. *
  2872. * @param $fh
  2873. * @param $interval
  2874. * @param $num_read
  2875. * @param $line_num
  2876. * @param $filesize
  2877. *
  2878. * @ingroup gff3_loader
  2879. */
  2880. private function loadFasta($fh, $interval, &$num_read, &$line_num, $filesize) {
  2881. $this->logMessage("Loading FASTA sequences...");
  2882. $residues = '';
  2883. $id = NULL;
  2884. // iterate through the remaining lines of the file
  2885. while ($line = fgets($fh)) {
  2886. $line_num++;
  2887. $size = drupal_strlen($line);
  2888. $this->addItemsHandled($size);
  2889. $num_read += $size;
  2890. $line = trim($line);
  2891. // if we encounter a definition line then get the name, uniquename,
  2892. // accession and relationship subject from the definition line
  2893. if (preg_match('/^>/', $line)) {
  2894. // if we are beginning a new sequence then save to the database the last one we just finished.
  2895. if ($id) {
  2896. $values = ['uniquename' => $id];
  2897. $result = chado_select_record('tripal_gff_temp', ['*'], $values);
  2898. if (count($result) == 0) {
  2899. $this->logMessage('Cannot find feature to assign FASTA sequence: %uname.',
  2900. ['%uname' => $id], TRIPAL_WARNING);
  2901. }
  2902. else {
  2903. // if we have a feature then add the residues
  2904. $feature = $result[0];
  2905. $values = [
  2906. 'residues' => $residues,
  2907. 'seqlen' => strlen($residues),
  2908. ];
  2909. $match = ['feature_id' => $feature->feature_id];
  2910. chado_update_record('feature', $match, $values);
  2911. }
  2912. }
  2913. // get the feature ID for this ID from the tripal_gff_temp table. It
  2914. // should be the name up to the first space
  2915. $id = preg_replace('/^>([^\s]+).*$/', '\1', $line);
  2916. $residues = '';
  2917. }
  2918. else {
  2919. $residues .= trim($line);
  2920. }
  2921. }
  2922. // add in the last sequence
  2923. $values = ['uniquename' => $id];
  2924. $result = chado_select_record('tripal_gff_temp', ['*'], $values);
  2925. if (count($result) == 0) {
  2926. $this->logMessage('Cannot find feature to assign FASTA sequence: %uname.',
  2927. ['%uname' => $id], TRIPAL_WARNING);
  2928. }
  2929. else {
  2930. // if we have a feature then add the residues
  2931. $feature = $result[0];
  2932. $values = [
  2933. 'residues' => $residues,
  2934. 'seqlen' => strlen($residues),
  2935. ];
  2936. $match = ['feature_id' => $feature->feature_id];
  2937. chado_update_record('feature', $match, $values);
  2938. }
  2939. }
  2940. /**
  2941. * Load the target attribute of a gff3 record
  2942. *
  2943. * @param $feature
  2944. * @param $tags
  2945. * @param $target_organism_id
  2946. * @param $target_type
  2947. * @param $create_target
  2948. * @param $attr_locgroup
  2949. *
  2950. * @ingroup gff3_loader
  2951. */
  2952. private function loadTarget($feature, $tags, $target_organism_id, $target_type, $create_target, $attr_locgroup) {
  2953. // format is: "target_id start end [strand]", where strand is optional and may be "+" or "-"
  2954. $matched = preg_match('/^(.*?)\s+(\d+)\s+(\d+)(\s+[\+|\-])*$/', trim($tags['Target'][0]), $matches);
  2955. // the organism and type of the target may also be specified as an attribute. If so, then get that
  2956. // information
  2957. $gff_target_organism = array_key_exists('target_organism', $tags) ? $tags['target_organism'][0] : '';
  2958. $gff_target_type = array_key_exists('target_type', $tags) ? $tags['target_type'][0] : '';
  2959. // if we have matches and the Target is in the correct format then load the alignment
  2960. if ($matched) {
  2961. $target_feature = $matches[1];
  2962. $start = $matches[2];
  2963. $end = $matches[3];
  2964. // if we have an optional strand, convert it to a numeric value.
  2965. if (!empty($matches[4])) {
  2966. if (preg_match('/^\+$/', trim($matches[4]))) {
  2967. $target_strand = 1;
  2968. }
  2969. elseif (preg_match('/^\-$/', trim($matches[4]))) {
  2970. $target_strand = -1;
  2971. }
  2972. else {
  2973. $target_strand = 0;
  2974. }
  2975. }
  2976. else {
  2977. $target_strand = 0;
  2978. }
  2979. $target_fmin = $start - 1;
  2980. $target_fmax = $end;
  2981. if ($end < $start) {
  2982. $target_fmin = $end - 1;
  2983. $target_fmax = $start;
  2984. }
  2985. // default the target organism to be the value passed into the function, but if the GFF
  2986. // file species the target organism then use that instead.
  2987. $t_organism_id = $target_organism_id;
  2988. if ($gff_target_organism) {
  2989. // get the genus and species
  2990. $success = preg_match('/^(.*?):(.*?)$/', $gff_target_organism, $matches);
  2991. if ($success) {
  2992. $values = [
  2993. 'genus' => $matches[1],
  2994. 'species' => $matches[2],
  2995. ];
  2996. $torganism = chado_select_record('organism', ['organism_id'], $values);
  2997. if (count($torganism) == 1) {
  2998. $t_organism_id = $torganism[0]->organism_id;
  2999. }
  3000. else {
  3001. $this->logMessage("Cannot find organism for target %target.",
  3002. ['%target' => $gff_target_organism], TRIPAL_WARNING);
  3003. $t_organism_id = '';
  3004. }
  3005. }
  3006. else {
  3007. $this->logMessage("The target_organism attribute is improperly formatted: %target. " .
  3008. "It should be target_organism=genus:species.",
  3009. ['%target' => $gff_target_organism], TRIPAL_WARNING);
  3010. $t_organism_id = '';
  3011. }
  3012. }
  3013. // default the target type to be the value passed into the function, but if the GFF file
  3014. // species the target type then use that instead
  3015. $t_type_id = '';
  3016. if ($target_type) {
  3017. $values = [
  3018. 'name' => $target_type,
  3019. 'cv_id' => [
  3020. 'name' => 'sequence',
  3021. ],
  3022. ];
  3023. $type = chado_select_record('cvterm', ['cvterm_id'], $values);
  3024. if (count($type) == 1) {
  3025. $t_type_id = $type[0]->cvterm_id;
  3026. }
  3027. else {
  3028. throw new Exception(t("The target type does not exist in the sequence ontology: %type. ",
  3029. ['%type' => $target_type]));
  3030. }
  3031. }
  3032. if ($gff_target_type) {
  3033. $values = [
  3034. 'name' => $gff_target_type,
  3035. 'cv_id' => [
  3036. 'name' => 'sequence',
  3037. ],
  3038. ];
  3039. // get the cvterm_id for the target type
  3040. $type = chado_select_record('cvterm', ['cvterm_id'], $values);
  3041. if (count($type) == 1) {
  3042. $t_type_id = $type[0]->cvterm_id;
  3043. }
  3044. else {
  3045. // check to see if this is a synonym
  3046. $sql = "
  3047. SELECT CVTS.cvterm_id
  3048. FROM {cvtermsynonym} CVTS
  3049. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = CVTS.cvterm_id
  3050. INNER JOIN {cv} CV ON CV.cv_id = CVT.cv_id
  3051. WHERE CV.name = 'sequence' and CVTS.synonym = :synonym
  3052. ";
  3053. $synonym = chado_query($sql, [':synonym' => $gff_target_type])->fetchObject();
  3054. if ($synonym) {
  3055. $t_type_id = $synonym->cvterm_id;
  3056. }
  3057. else {
  3058. $this->logMessage("The target_type attribute does not exist in the sequence ontology: %type.",
  3059. ['%type' => $gff_target_type], TRIPAL_WARNING);
  3060. $t_type_id = '';
  3061. }
  3062. }
  3063. }
  3064. // we want to add a featureloc record that uses the target feature as the srcfeature (landmark)
  3065. // and the landmark as the feature.
  3066. $this->loadFeatureLoc($feature, NULL, $target_feature, $target_fmin,
  3067. $target_fmax, $target_strand, NULL, NULL, NULL, NULL,
  3068. $attr_locgroup, $t_type_id, $t_organism_id, $create_target, TRUE);
  3069. }
  3070. // the target attribute is not correctly formatted
  3071. else {
  3072. $this->logMessage("Could not add 'Target' alignment as it is improperly formatted: '%target'",
  3073. ['%target' => $tags['Target'][0]], TRIPAL_ERROR);
  3074. }
  3075. }
  3076. }