GFF3Importer.inc 133 KB

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