GFF3Importer.inc 124 KB

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