GFF3Importer.inc 122 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517
  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[$rid] = [
  823. 'uniquename' => $landmark->getValue('uniquename'),
  824. 'name' => $landmark->getValue('name'),
  825. 'type' => $this->landmark_cvterm->getValue('name'),
  826. 'feature_id' => $landmark->getValue('feature_id'),
  827. 'organism_id' => $landmark->getValue('organism_id'),
  828. ];
  829. }
  830. }
  831. }
  832. /**
  833. *
  834. */
  835. private function parseGFF3() {
  836. $filesize = filesize($this->gff_file);
  837. $this->setTotalItems($filesize);
  838. // Holds a unique list of cvterms for later lookup.
  839. $feature_cvterms = [];
  840. $featureprop_cvterms = [];
  841. while ($line = fgets($this->gff_file_h)) {
  842. $this->current_line++;
  843. $this->addItemsHandled(drupal_strlen($line));
  844. $line = trim($line);
  845. if ($this->current_line < $this->start_line) {
  846. continue;
  847. }
  848. // If we're in the FASTA file we're at the end of the features so return.
  849. if (preg_match('/^##FASTA/i', $line)) {
  850. $this->indexFASTA();
  851. continue;
  852. }
  853. // if at the ##sequence-region line handle it.
  854. $matches = [];
  855. if (preg_match('/^##sequence-region\s+(\w*?)\s+(\d+)\s+(\d+)$/i', $line, $matches)) {
  856. $this->seq_region_headers[$matches[1]] = $line;
  857. continue;
  858. }
  859. // skip comments
  860. if (preg_match('/^#/', $line)) {
  861. continue;
  862. }
  863. // skip empty lines
  864. if (preg_match('/^\s*$/', $line)) {
  865. continue;
  866. }
  867. // Parse this feature from this line of the GFF3 file.
  868. $gff_feature = $this->parseFeature($line);
  869. // Add the landmark if it doesn't exist in the landmark list.
  870. if (!array_key_exists($gff_feature['landmark'], $this->landmarks)) {
  871. $this->landmarks[$gff_feature['landmark']] = FALSE;
  872. }
  873. // Store this feature in the landmark list or the feature list.
  874. if ($gff_feature['uniquename'] == $gff_feature['landmark']) {
  875. $this->landmarks[$gff_feature['uniquename']] = $gff_feature;
  876. }
  877. else {
  878. $this->features[$gff_feature['uniquename']] = $gff_feature;
  879. }
  880. // Store any parent/child relationships
  881. if (array_key_exists('Parent', $gff_feature)) {
  882. // Add the parent relationship
  883. if (!array_key_exists($gff_feature['Parent'], $this->relationships['Parent'])) {
  884. $this->relationships['Parent'][$gff_feature['Parent']] = [];
  885. }
  886. if (!array_key_exists($gff_feature['type'], $this->relationships['Parent'][$gff_feature['Parent']])) {
  887. $this->relationships['Parent'][$gff_feature['Parent']][$gff_feature['type']] = [];
  888. }
  889. $this->relationships['Parent'][$gff_feature['Parent']][$gff_feature['type']][$gff_feature['start']] = $gff_feature['uniquename'];
  890. // Add the child relationship
  891. $this->relationships['Child'][$gff_feature['uniquename']] = $gff_feature['Parent'];
  892. }
  893. // Organize the CVterms for faster access later on.
  894. if (!array_key_exists($gff_feature['type'], $feature_cvterms)) {
  895. $feature_cvterms[$gff_feature['type']] = 0;
  896. }
  897. $feature_cvterms[$gff_feature['type']]++;
  898. // Organize the feature property types for faster access later on.
  899. foreach ($gff_feature['properties'] as $prop_name => $value) {
  900. if (!array_key_exists($prop_name, $featureprop_cvterms)) {
  901. $featureprop_cvterms[$prop_name] = 0;
  902. }
  903. $featureprop_cvterms[$prop_name]++;
  904. }
  905. }
  906. // Iterate through the feature type terms and get a chado object for each.
  907. $feature_cvterm_ids = [];
  908. foreach ($feature_cvterms as $name => $counts) {
  909. $cvterm_id = $this->getCvtermID($name, $this->feature_cv->getValue('cv_id'), FALSE);
  910. $feature_cvterm_ids[] = $cvterm_id;
  911. }
  912. // Iterate through the featureprop type terms and get a cvterm_id for
  913. // each. If it doesn't exist then add a new record.
  914. foreach ($featureprop_cvterms as $name => $counts) {
  915. $cvterm_id = $this->getCvtermID($name, $this->feature_prop_cv->getValue('cv_id'), TRUE);
  916. if (!$cvterm_id) {
  917. $term = [
  918. 'id' => "local:$name",
  919. 'name' => $name,
  920. 'is_obsolete' => 0,
  921. 'cv_name' => $this->feature_prop_cv->getValue('name'),
  922. 'db_name' => 'local',
  923. 'is_relationship' => FALSE,
  924. ];
  925. $cvterm = (object) chado_insert_cvterm($term, ['update_existing' => FALSE]);
  926. if (!$cvterm) {
  927. $this->logMessage("Cannot add cvterm, $name.", [], TRIPAL_WARNING);
  928. return 0;
  929. }
  930. $this->featureprop_cvterm_lookup[$cvterm->name] = $cvterm->cvterm_id;
  931. }
  932. }
  933. // Now, get a list of features for this organism and the given types
  934. // we will use this list to do an "in-memory" lookup to make sure we
  935. // are not violating the unique contraint of the feature table
  936. // prior to inserting the features.
  937. $sql = "
  938. SELECT F.uniquename, CVT.name as type
  939. FROM {feature} F
  940. INNER JOIN {cvterm} CVT on F.type_id = CVT.cvterm_id
  941. WHERE organism_id = :organism_id and type_id IN (:types)
  942. ";
  943. $result = chado_query($sql, [
  944. ':organism_id' => $this->organism_id,
  945. ':types' => $feature_cvterm_ids,
  946. ]);
  947. while ($feature = $result->fetchObject()) {
  948. $this->feature_lookup[$feature->organism_id][$feature->type][$feature->uniquename] = TRUE;
  949. }
  950. }
  951. /**
  952. * Imports the landmark features into Chado.
  953. */
  954. private function loadLandmarks() {
  955. $new_landmarks = [];
  956. foreach ($this->landmarks as $uniquename => $feature) {
  957. // If the landmark does not have an entry in the GFF lines, try to
  958. // find it in the heade (i.e. ##sequence-region section). If it
  959. // exists then create it.
  960. if ($feature === FALSE) {
  961. if (array_key_exists($uniquename, $this->seq_region_headers)) {
  962. $this->loadHeaderLandmark($this->seq_region_headers[$uniquename]);
  963. continue;
  964. }
  965. else {
  966. 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.',
  967. ['!landmark' => $uniquename]));
  968. }
  969. }
  970. else {
  971. $new_landmarks[$uniquename] = $feature;
  972. }
  973. }
  974. $this->loadFeatures($new_landmarks);
  975. }
  976. /**
  977. * Indicates if the feature is already loaded in the database.
  978. */
  979. private function doesFeatureAlreadyExist(&$feature) {
  980. if (array_key_exists($feature['type'], $this->feature_cvterm_aliases)) {
  981. $feature['type'] = $this->feature_cvterm_aliases[$feature['type']];
  982. }
  983. if (array_key_exists($feature->organism_id, $this->feature_lookup) and
  984. array_key_exists($feature['type'], $this->feature_lookup[$feature->organism_id]) and
  985. array_key_exists($feature['uniquename'], $this->feature_lookup[$feature->organism_id][$feature['type']])){
  986. return TRUE;
  987. }
  988. return FALSE;
  989. }
  990. /**
  991. *
  992. * @param unknown $feature
  993. * @throws Exception
  994. */
  995. private function ensureFeatureIsLoaded($feature) {
  996. // If this feature doesn't have a feature_id then someting is wrong.
  997. if (!array_key_exists('feature_id', $feature)) {
  998. throw new Exception(t('The feature, !feature, is in the GFF but somehow was not added to the database.',
  999. ['!feature' => $uniquename . " (" . $feature['name'] . ") at line " . $feature['line'] . '.']));
  1000. }
  1001. }
  1002. /**
  1003. * Imports the feature records into Chado.
  1004. */
  1005. private function loadFeatures($features) {
  1006. $batch_size = 1000;
  1007. $num_features = count(array_keys($features));
  1008. $num_batches = (int) ($num_features / $batch_size) + 1;
  1009. $this->setItemsHandled(0);
  1010. $this->setTotalItems($num_batches);
  1011. // Get the current max feature id prior to inserting the batch so
  1012. // we can retrieve the feature_ids of what was inserted afterwards.
  1013. $result = chado_query("SELECT max(feature_id) AS max_id FROM {feature}");
  1014. $start_id = $result->fetchField();
  1015. // If the feature table is empty, we need to set the start to 1.
  1016. if (!$start_id) {
  1017. $start_id = 1;
  1018. }
  1019. $init_sql = "
  1020. INSERT INTO {feature}
  1021. (uniquename, name, type_id, organism_id, residues, md5checksum,
  1022. seqlen, is_analysis, is_obsolete)
  1023. VALUES\n";
  1024. $i = 0;
  1025. $batch_num = 1;
  1026. $sql = '';
  1027. $args = [];
  1028. foreach ($features as $uniquename => $feature) {
  1029. // Only do an insert if this feature doesn't already exist in the databse.
  1030. if (!$this->doesFeatureAlreadyExist($feature)) {
  1031. $i++;
  1032. $residues = $this->getResidues($feature, FALSE);
  1033. $sql .= "(:uniquename_$i, :name_$i, :type_id_$i, :organism_id_$i, :residues_$i, " .
  1034. " :md5checksum_$i, :seqlen_$i, FALSE, FALSE),\n";
  1035. $args[":uniquename_$i"] = $feature['uniquename'];
  1036. $args[":name_$i"] = $feature['name'];
  1037. $args[":type_id_$i"] = $this->feature_cvterm_lookup[$feature['type']];
  1038. $args[":organism_id_$i"] = $feature['organism_id'];
  1039. $args[":residues_$i"] = $residues;
  1040. $args[":md5checksum_$i"] = $residues ? md5($residues) : '';
  1041. $args[":seqlen_$i"] = strlen($residues);
  1042. // If we've reached the size of the batch then let's do the insert.
  1043. if ($i == $batch_size) {
  1044. // Insert the batch.
  1045. $sql = rtrim($sql, ",\n");
  1046. $sql = $init_sql . $sql;
  1047. $last_id = chado_query($sql, $args, ['return' => Database::RETURN_INSERT_ID]);
  1048. $this->assignFeatureIDs($start_id, $last_id);
  1049. $this->setItemsHandled($batch_num);
  1050. $batch_num++;
  1051. // Now reset all of the varables for the next batch.
  1052. $sql = '';
  1053. $i = 0;
  1054. $args = [];
  1055. $start_id = $last_id;
  1056. }
  1057. }
  1058. }
  1059. // Insert any remaining batch items
  1060. if ($i > 0) {
  1061. $sql = rtrim($sql, ",\n");
  1062. $sql = $init_sql . $sql;
  1063. $last_id = chado_query($sql, $args, ['return' => Database::RETURN_INSERT_ID]);
  1064. $this->assignFeatureIDs($start_id, $last_id);
  1065. $this->setItemsHandled($batch_num);
  1066. }
  1067. }
  1068. /**
  1069. * Adds the feature IDs to features within a range if feature_ids.
  1070. *
  1071. * The start and last IDs should corresopnd to Id's surrounding
  1072. * a batch insert of features.
  1073. */
  1074. private function assignFeatureIDs($start_id, $last_id) {
  1075. // Get the feature Ids for the batch sequences
  1076. $sql = "
  1077. SELECT feature_id, uniquename
  1078. FROM {feature} F
  1079. WHERE feature_id > $start_id and feature_id <= $last_id
  1080. ";
  1081. $results = chado_query($sql);
  1082. while ($result = $results->fetchObject()) {
  1083. if (array_key_exists($result->uniquename, $this->features)) {
  1084. $this->features[$result->uniquename]['feature_id'] = $result->feature_id;
  1085. }
  1086. if (array_key_exists($result->uniquename, $this->landmarks)) {
  1087. $this->landmarks[$result->uniquename]['feature_id'] = $result->feature_id;
  1088. }
  1089. }
  1090. }
  1091. /**
  1092. *
  1093. */
  1094. private function loadProperties(){
  1095. $batch_size = 100;
  1096. $num_features = count(array_keys($this->features));
  1097. $num_batches = (int) ($num_features / $batch_size) + 1;
  1098. $this->setItemsHandled(0);
  1099. $this->setTotalItems($num_batches);
  1100. $init_sql = "
  1101. INSERT INTO {featureprop}
  1102. (feature_id, type_id, value, rank)
  1103. VALUES\n";
  1104. $i = 0;
  1105. $j = 0;
  1106. $batch_num = 1;
  1107. $sql = '';
  1108. $args = [];
  1109. foreach ($this->features as $uniquename => $feature) {
  1110. // Only do an insert if this feature doesn't already exist in the databse.
  1111. if (!$this->doesFeatureAlreadyExist($feature)) {
  1112. $i++;
  1113. $this->ensureFeatureIsLoaded($feature);
  1114. // Iterate through all of the properties of this feature.
  1115. foreach ($feature['properties'] as $prop_name => $values) {
  1116. foreach ($values as $rank => $value) {
  1117. $j++;
  1118. $sql .= "(:feature_id_$j, :type_id_$j, :value_$j, :rank_$j),\n";
  1119. $args[":feature_id_$j"] = $feature['feature_id'];
  1120. $args[":type_id_$j"] = $this->featureprop_cvterm_lookup[$prop_name];
  1121. $args[":value_$j"] = $value;
  1122. $args[":rank_$j"] = $rank;
  1123. }
  1124. }
  1125. // If we've reached the size of the batch then let's do the insert.
  1126. if ($i == $batch_size) {
  1127. // Insert the batch.
  1128. $sql = rtrim($sql, ",\n");
  1129. $sql = $init_sql . $sql;
  1130. $last_id = chado_query($sql, $args, ['return' => Database::RETURN_INSERT_ID]);
  1131. $this->setItemsHandled($batch_num);
  1132. $batch_num++;
  1133. // Now reset all of the varables for the next batch.
  1134. $sql = '';
  1135. $i = 0;
  1136. $j = 0;
  1137. $args = [];
  1138. }
  1139. }
  1140. }
  1141. // Add any remaining batch items
  1142. if ($i > 0) {
  1143. $sql = rtrim($sql, ",\n");
  1144. $sql = $init_sql . $sql;
  1145. $last_id = chado_query($sql, $args, ['return' => Database::RETURN_INSERT_ID]);
  1146. $this->setItemsHandled($batch_num);
  1147. }
  1148. }
  1149. /**
  1150. *
  1151. */
  1152. private function loadDbxrefs() {
  1153. }
  1154. /**
  1155. *
  1156. */
  1157. private function loadFeatureLocs() {
  1158. $batch_size = 1000;
  1159. $num_features = count(array_keys($this->features));
  1160. $num_batches = (int) ($num_features / $batch_size) + 1;
  1161. $this->setItemsHandled(0);
  1162. $this->setTotalItems($num_batches);
  1163. $init_sql = "
  1164. INSERT INTO {featureloc}
  1165. (srcfeature_id, feature_id, fmin, fmax, strand, phase, rank)
  1166. VALUES\n";
  1167. $i = 0;
  1168. $batch_num = 1;
  1169. $sql = '';
  1170. $args = [];
  1171. foreach ($this->features as $uniquename => $feature) {
  1172. // Only do an insert if this feature doesn't already exist in the databse.
  1173. if (!$this->doesFeatureAlreadyExist($feature)) {
  1174. $i++;
  1175. $this->ensureFeatureIsLoaded($feature);
  1176. // Get the rank of this feature by ordering all of the other
  1177. // subfeatures of the same type that share the same parent.
  1178. // Order them by the fmin and use the index of this feature as the
  1179. // rank.
  1180. $rank = 0;
  1181. if (array_key_exists('Parent', $feature)) {
  1182. $coords = array_keys($this->relationships['Parent'][$feature['Parent']][$feature['type']]);
  1183. sort($coords);
  1184. $rank = array_search($feature['start'], $coords);
  1185. }
  1186. $sql .= "(:srcfeature_id_$i, :feature_id_$i, :fmin_$i, :fmax_$i," .
  1187. " :strand_$i, :phase_$i, :rank_$i),\n";
  1188. $args[":srcfeature_id_$i"] = $this->landmarks[$feature['landmark']]['feature_id'];
  1189. $args[":feature_id_$i"] = $feature['feature_id'];
  1190. $args[":fmin_$i"] = $feature['start'];
  1191. $args[":fmax_$i"] = $feature['end'];
  1192. $args[":strand_$i"] = $feature['strand'];
  1193. $args[":phase_$i"] = $feature['phase'] ? $feature['phase'] : NULL;
  1194. $args[":rank_$i"] = $rank;
  1195. // If we've reached the size of the batch then let's do the insert.
  1196. if ($i == $batch_size) {
  1197. // Insert the batch.
  1198. $sql = rtrim($sql, ",\n");
  1199. $sql = $init_sql . $sql;
  1200. //$last_id = chado_query($sql, $args, ['return' => Database::RETURN_INSERT_ID]);
  1201. $this->setItemsHandled($batch_num);
  1202. $batch_num++;
  1203. // Now reset all of the varables for the next batch.
  1204. $sql = '';
  1205. $i = 0;
  1206. $args = [];
  1207. }
  1208. }
  1209. }
  1210. // Add any remaining batch items
  1211. if ($i > 0) {
  1212. $sql = rtrim($sql, ",\n");
  1213. $sql = $init_sql . $sql;
  1214. $last_id = chado_query($sql, $args, ['return' => Database::RETURN_INSERT_ID]);
  1215. $this->setItemsHandled($batch_num);
  1216. }
  1217. }
  1218. /**
  1219. *
  1220. */
  1221. private function loadAliases(){
  1222. $batch_size = 1000;
  1223. $num_features = count(array_keys($this->features));
  1224. $num_batches = (int) ($num_features / $batch_size) + 1;
  1225. $this->setItemsHandled(0);
  1226. $this->setTotalItems($num_batches);
  1227. $init_syn_sql = "INSERT INTO {synonym} (name, type_id, synonym_sgml) VALUES \n";
  1228. $init_fsyn_sql = "INSERT INTO {feature_synonym} (synonym_id, feature_id, pub_id) VALUES \n";
  1229. $i = 0;
  1230. $batch_num = 1;
  1231. $syn_sql = '';
  1232. $syn_args = [];
  1233. $fsyn_sql = '';
  1234. $fsyn_args = [];
  1235. $batch_synonyms = [];
  1236. $batch_featuresyn = [];
  1237. foreach ($this->features as $uniquename => $feature) {
  1238. // Only do an insert if this feature doesn't already exist in the databse.
  1239. if (!$this->doesFeatureAlreadyExist($feature)) {
  1240. $i++;
  1241. $this->ensureFeatureIsLoaded($feature);
  1242. // Get all of the synonyms for this batch.
  1243. foreach ($feature['synonyms'] as $index => $synonym) {
  1244. $batch_synonyms[] = $synonym;
  1245. $batch_featuresyn[] = [$synonym, $feature['feature_id']];
  1246. }
  1247. // If we've reached the size of the batch then let's do the insert.
  1248. if ($i == $batch_size) {
  1249. if (count($batch_synonyms) > 0) {
  1250. // First get the synonym_ids for those already in the database.
  1251. $syns_avail_sql = "SELECT synonym_id, name FROM {synonym} WHERE type_id = :type_id and name IN (:names)";
  1252. $syns_avail_args = [
  1253. ':type_id' => $this->exact_syn->cvterm_id,
  1254. ':names' => $batch_synonyms
  1255. ];
  1256. $syns_avail = chado_query($syns_avail_sql, $syns_avail_args)->fetchAllAssoc('name', PDO::FETCH_OBJ);
  1257. // First, add any missing synonyms
  1258. $j = 0;
  1259. foreach ($batch_synonyms as $index => $synonym) {
  1260. if (!array_key_exists($synonym, $syns_avail)) {
  1261. $j++;
  1262. $syn_sql .= "(:name_$j, :type_id_$j, ''),\n";
  1263. $syn_args[":name_$j"] = $synonym;
  1264. $syn_args[":type_id_$j"] = $this->exact_syn->cvterm_id;
  1265. }
  1266. }
  1267. if ($syn_sql) {
  1268. $syn_sql = rtrim($syn_sql, ",\n");
  1269. $syn_sql = $init_syn_sql . $syn_sql;
  1270. $last_id = chado_query($syn_sql, $syn_args, ['return' => Database::RETURN_INSERT_ID]);
  1271. $syns_avail = chado_query($syns_avail_sql, $syns_avail_args)->fetchAllAssoc('name', PDO::FETCH_OBJ);
  1272. }
  1273. // Add in the feature synonym records for this batch.
  1274. $j = 0;
  1275. foreach ($batch_featuresyn as $index => $featuresyn) {
  1276. $j++;
  1277. $fsyn_sql .= "(:synonym_id_$j, :feature_id_$j, :pub_id_$j),\n";
  1278. $fsyn_args[":synonym_id_$j"] = $syns_avail[$featuresyn[0]]->synonym_id;
  1279. $fsyn_args[":feature_id_$j"] = $featuresyn[1];
  1280. $fsyn_args[":pub_id_$j"] = $this->null_pub->pub_id;
  1281. }
  1282. $fsyn_sql = rtrim($fsyn_sql, ",\n");
  1283. $fsyn_sql = $init_fsyn_sql . $fsyn_sql;
  1284. $last_id = chado_query($fsyn_sql, $fsyn_args, ['return' => Database::RETURN_INSERT_ID]);
  1285. }
  1286. $this->setItemsHandled($batch_num);
  1287. // Now reset all of the varables for the next batch.
  1288. $syn_sql = '';
  1289. $fsyn_sql = '';
  1290. $i = 0;
  1291. $syn_args = [];
  1292. $fsyn_args = [];
  1293. $batch_synonyms = [];
  1294. $batch_featuresyn = [];
  1295. }
  1296. }
  1297. }
  1298. // Add any remaining batch items
  1299. if ($i > 0) {
  1300. if (count($batch_synonyms) > 0) {
  1301. // First get the synonym_ids for those already in the database.
  1302. $syns_avail_sql = "SELECT synonym_id, name FROM {synonym} WHERE type_id = :type_id and name IN (:names)";
  1303. $syns_avail_args = [
  1304. ':type_id' => $this->exact_syn->cvterm_id,
  1305. ':names' => $batch_synonyms
  1306. ];
  1307. $syns_avail = chado_query($syns_avail_sql, $syns_avail_args)->fetchAllAssoc('name', PDO::FETCH_OBJ);
  1308. // First, add any missing synonyms
  1309. $j = 0;
  1310. foreach ($batch_synonyms as $index => $synonym) {
  1311. if (!array_key_exists($synonym, $syns_avail)) {
  1312. $j++;
  1313. $syn_sql .= "(:name_$j, :type_id_$j, ''),\n";
  1314. $syn_args[":name_$j"] = $synonym;
  1315. $syn_args[":type_id_$j"] = $this->exact_syn->cvterm_id;
  1316. }
  1317. }
  1318. if ($syn_sql) {
  1319. $syn_sql = rtrim($syn_sql, ",\n");
  1320. $syn_sql = $init_syn_sql . $syn_sql;
  1321. $last_id = chado_query($syn_sql, $syn_args, ['return' => Database::RETURN_INSERT_ID]);
  1322. $syns_avail = chado_query($syns_avail_sql, $syns_avail_args)->fetchAllAssoc('name', PDO::FETCH_OBJ);
  1323. }
  1324. // Add in the feature synonym records for this batch.
  1325. $j = 0;
  1326. foreach ($batch_featuresyn as $index => $featuresyn) {
  1327. $j++;
  1328. $fsyn_sql .= "(:synonym_id_$j, :feature_id_$j, :pub_id_$j),\n";
  1329. $fsyn_args[":synonym_id_$j"] = $syns_avail[$featuresyn[0]]->synonym_id;
  1330. $fsyn_args[":feature_id_$j"] = $featuresyn[1];
  1331. $fsyn_args[":pub_id_$j"] = $this->null_pub->pub_id;
  1332. }
  1333. $fsyn_sql = rtrim($fsyn_sql, ",\n");
  1334. $fsyn_sql = $init_fsyn_sql . $fsyn_sql;
  1335. $last_id = chado_query($fsyn_sql, $fsyn_args, ['return' => Database::RETURN_INSERT_ID]);
  1336. }
  1337. $this->setItemsHandled($batch_num);
  1338. }
  1339. }
  1340. /**
  1341. * Load a GFF3 file. This is the function called by tripal jobs
  1342. *
  1343. * @ingroup gff3_loader
  1344. */
  1345. private function loadGFF3() {
  1346. $ret = [];
  1347. $date = getdate();
  1348. $filesize = filesize($this->gff_file);
  1349. $this->setTotalItems($filesize);
  1350. $in_fasta = 0;
  1351. $line_num = 0;
  1352. $num_read = 0;
  1353. // iterate through each line of the GFF file
  1354. while ($line = fgets($this->gff_file_h)) {
  1355. $line_num++;
  1356. $this->line_num = $line_num;
  1357. $size = drupal_strlen($line);
  1358. $this->addItemsHandled($size);
  1359. $num_read += $size;
  1360. if ($line_num < $this->start_line) {
  1361. continue;
  1362. }
  1363. // check to see if we have FASTA section, if so then set the variable
  1364. // to start parsing
  1365. if (preg_match('/^##FASTA/i', $line)) {
  1366. $this->logMessage("Parsing FASTA portion...");
  1367. if ($remove) {
  1368. // we're done because this is a delete operation so break out of the loop.
  1369. break;
  1370. }
  1371. $this->loadFasta($fh, $interval, $num_read, $line_num, $filesize);
  1372. continue;
  1373. }
  1374. // if the ##sequence-region line is present then we want to add a new feature
  1375. if (preg_match('/^##sequence-region\s+(\w*?)\s+(\d+)\s+(\d+)$/i', $line, $region_matches)) {
  1376. $rid = $region_matches[1];
  1377. $rstart = $region_matches[2];
  1378. $rend = $region_matches[3];
  1379. if ($landmark_type) {
  1380. $this->loadFeature($organism, $analysis_id, $landmark_cvterm, $rid,
  1381. $rid, '', 'f', 'f', 1, 0);
  1382. }
  1383. continue;
  1384. }
  1385. // skip comments
  1386. if (preg_match('/^#/', $line)) {
  1387. continue;
  1388. }
  1389. // skip empty lines
  1390. if (preg_match('/^\s*$/', $line)) {
  1391. continue;
  1392. }
  1393. // get the columns
  1394. $cols = explode("\t", $line);
  1395. if (sizeof($cols) != 9) {
  1396. throw new Exception(t('Improper number of columns on line %line_num', ['%line_num' => $line_num]));
  1397. }
  1398. // get the column values
  1399. $landmark = $cols[0];
  1400. $source = $cols[1];
  1401. $type = $cols[2];
  1402. $start = $cols[3];
  1403. $end = $cols[4];
  1404. $score = $cols[5];
  1405. $strand = $cols[6];
  1406. $phase = $cols[7];
  1407. $attrs = explode(";", $cols[8]); // split by a semicolon
  1408. // ready the start and stop for chado. Chado expects these positions
  1409. // to be zero-based, so we substract 1 from the fmin
  1410. $fmin = $start - 1;
  1411. $fmax = $end;
  1412. if ($end < $start) {
  1413. $fmin = $end - 1;
  1414. $fmax = $start;
  1415. }
  1416. // format the strand for chado
  1417. if (strcmp($strand, '.') == 0) {
  1418. $strand = 0;
  1419. }
  1420. elseif (strcmp($strand, '+') == 0) {
  1421. $strand = 1;
  1422. }
  1423. elseif (strcmp($strand, '-') == 0) {
  1424. $strand = -1;
  1425. }
  1426. if (strcmp($phase, '.') == 0) {
  1427. if ($type == 'CDS') {
  1428. $phase = '0';
  1429. }
  1430. else {
  1431. $phase = '';
  1432. }
  1433. }
  1434. $cvterm = $this->getCvterm($type);
  1435. if (!$cvterm) {
  1436. throw new Exception(t('Cannot find feature term \'%type\' on line %line_num of the GFF file',
  1437. ['%type' => $type, '%line_num' => $line_num]));
  1438. }
  1439. // break apart each of the attributes
  1440. $tags = [];
  1441. $attr_name = '';
  1442. $attr_uniquename = '';
  1443. $attr_residue_info = '';
  1444. $attr_locgroup = 0;
  1445. $attr_fmin_partial = 'f';
  1446. $attr_fmax_partial = 'f';
  1447. $attr_is_obsolete = 'f';
  1448. $attr_is_analysis = 'f';
  1449. $attr_others = [];
  1450. $residues = '';
  1451. // the organism to which a feature belongs can be set in the GFF
  1452. // file using the 'organism' attribute. By default we
  1453. // set the $feature_organism variable to the default organism for the landmark
  1454. $attr_organism = '';
  1455. $feature_organism = $organism;
  1456. foreach ($attrs as $attr) {
  1457. $attr = rtrim($attr);
  1458. $attr = ltrim($attr);
  1459. if (strcmp($attr, '') == 0) {
  1460. continue;
  1461. }
  1462. if (!preg_match('/^[^\=]+\=.+$/', $attr)) {
  1463. throw new Exception(t('Attribute is not correctly formatted on line %line_num: %attr',
  1464. ['%line_num' => $line_num, '%attr' => $attr]));
  1465. }
  1466. // break apart each tag
  1467. $tag = preg_split("/=/", $attr, 2); // split by equals sign
  1468. // multiple instances of an attribute are separated by commas
  1469. $tag_name = $tag[0];
  1470. if (!array_key_exists($tag_name, $tags)) {
  1471. $tags[$tag_name] = [];
  1472. }
  1473. $tags[$tag_name] = array_merge($tags[$tag_name], explode(",", $tag[1])); // split by comma
  1474. // replace the URL escape codes for each tag
  1475. for ($i = 0; $i < count($tags[$tag_name]); $i++) {
  1476. $tags[$tag_name][$i] = urldecode($tags[$tag_name][$i]);
  1477. }
  1478. // get the name and ID tags
  1479. $skip_feature = 0; // if there is a problem with any of the attributes this variable gets set
  1480. if (strcmp($tag_name, 'ID') == 0) {
  1481. $attr_uniquename = urldecode($tag[1]);
  1482. }
  1483. elseif (strcmp($tag_name, 'Name') == 0) {
  1484. $attr_name = urldecode($tag[1]);
  1485. }
  1486. elseif (strcmp($tag_name, 'organism') == 0) {
  1487. $attr_organism = urldecode($tag[1]);
  1488. $org_matches = [];
  1489. if (preg_match('/^(.*?):(.*?)$/', $attr_organism, $org_matches)) {
  1490. $values = [
  1491. 'genus' => $org_matches[1],
  1492. 'species' => $org_matches[2],
  1493. ];
  1494. $org = chado_select_record('organism', ["*"], $values);
  1495. if (count($org) == 0) {
  1496. if ($create_organism) {
  1497. $feature_organism = (object) chado_insert_record('organism', $values, array(
  1498. 'skip_validation' => TRUE,
  1499. ));
  1500. if (!$feature_organism) {
  1501. $this->logMessage("Could not add the organism, '%org', from line %line. Skipping this line.",
  1502. [
  1503. '%org' => $attr_organism,
  1504. '%line' => $line_num,
  1505. ], TRIPAL_ERROR);
  1506. $skip_feature = 1;
  1507. }
  1508. }
  1509. else {
  1510. $this->logMessage("The organism attribute '%org' on line %line does not exist. Skipping this line.",
  1511. [
  1512. '%org' => $attr_organism,
  1513. '%line' => $line_num,
  1514. ], TRIPAL_ERROR);
  1515. $skip_feature = 1;
  1516. }
  1517. }
  1518. else {
  1519. // We found the organism in the database so use it.
  1520. $feature_organism = $org[0];
  1521. }
  1522. }
  1523. else {
  1524. $this->logMessage("The organism attribute '%org' on line %line is not properly formated. It " .
  1525. "should be of the form: organism=Genus:species. Skipping this line.",
  1526. ['%org' => $attr_organism, '%line' => $line_num], TRIPAL_ERROR);
  1527. $skip_feature = 1;
  1528. }
  1529. }
  1530. // Get the list of non-reserved attributes.
  1531. elseif (strcmp($tag_name, 'Alias') != 0 and strcmp($tag_name, 'Parent') != 0 and
  1532. strcmp($tag_name, 'Target') != 0 and strcmp($tag_name, 'Gap') != 0 and
  1533. strcmp($tag_name, 'Derives_from') != 0 and strcmp($tag_name, 'Note') != 0 and
  1534. strcmp($tag_name, 'Dbxref') != 0 and strcmp($tag_name, 'Ontology_term') != 0 and
  1535. strcmp($tag_name, 'Is_circular') != 0 and strcmp($tag_name, 'target_organism') != 0 and
  1536. strcmp($tag_name, 'target_type') != 0 and strcmp($tag_name, 'organism' != 0)) {
  1537. foreach ($tags[$tag_name] as $value) {
  1538. $attr_others[$tag_name][] = $value;
  1539. }
  1540. }
  1541. }
  1542. // If neither name nor uniquename are provided then generate one.
  1543. if (!$attr_uniquename and !$attr_name) {
  1544. // Check if an alternate ID field is suggested, if so, then use
  1545. // that for the name.
  1546. if (array_key_exists($alt_id_attr, $tags)) {
  1547. $attr_uniquename = $tags[$alt_id_attr][0];
  1548. $attr_name = $attr_uniquename;
  1549. }
  1550. // If the row has a parent then generate a uniquename using the parent name
  1551. // add the date to the name in the event there are more than one child with
  1552. // the same parent.
  1553. elseif (array_key_exists('Parent', $tags)) {
  1554. $attr_uniquename = $tags['Parent'][0] . "-$type-$landmark-" . $date[0] . ":" . ($fmin + 1) . ".." . $fmax;
  1555. $attr_name = $attr_uniquename;
  1556. }
  1557. // Generate a unique name based on the date, type and location
  1558. // and set the name to simply be the type.
  1559. else {
  1560. $attr_uniquename = $date[0] . "-$type-$landmark:" . ($fmin + 1) . ".." . $fmax;
  1561. $attr_name = $type;
  1562. }
  1563. }
  1564. // If a name is not specified then use the unique name as the name
  1565. if (strcmp($attr_name, '') == 0) {
  1566. $attr_name = $attr_uniquename;
  1567. }
  1568. // If an ID attribute is not specified then we must generate a
  1569. // unique ID. Do this by combining the attribute name with the date
  1570. // and line number.
  1571. if (!$attr_uniquename) {
  1572. $attr_uniquename = $attr_name . '-' . $date[0] . '-' . $line_num;
  1573. }
  1574. // Make sure the landmark sequence exists in the database. If the user
  1575. // has not specified a landmark type (and it's not required in the GFF
  1576. // format) then we don't know the type of the landmark so we'll hope
  1577. // that it's unique across all types for the organism. Only do this
  1578. // test if the landmark and the feature are different.
  1579. if (!$remove and !(strcmp($landmark, $attr_uniquename) == 0 or strcmp($landmark, $attr_name) == 0) and !in_array($landmark, $landmark_lookup)) {
  1580. $select = [
  1581. 'organism_id' => $organism->organism_id,
  1582. 'uniquename' => $landmark,
  1583. ];
  1584. $columns = ['count(*) as num_landmarks'];
  1585. if ($landmark_type) {
  1586. $select['type_id'] = [
  1587. 'name' => $landmark_type,
  1588. ];
  1589. }
  1590. $count = chado_select_record('feature', $columns, $select);
  1591. if (!$count or count($count) == 0 or $count[0]->num_landmarks == 0) {
  1592. // now look for the landmark using the name rather than uniquename.
  1593. $select = [
  1594. 'organism_id' => $organism->organism_id,
  1595. 'name' => $landmark,
  1596. ];
  1597. $columns = ['count(*) as num_landmarks'];
  1598. if ($landmark_type) {
  1599. $select['type_id'] = [
  1600. 'name' => $landmark_type,
  1601. ];
  1602. }
  1603. $count = chado_select_record('feature', $columns, $select);
  1604. if (!$count or count($count) == 0 or $count[0]->num_landmarks == 0) {
  1605. throw new Exception(t("The landmark '%landmark' cannot be found for this organism (%species) " .
  1606. "Please add the landmark and then retry the import of this GFF3 " .
  1607. "file", [
  1608. '%landmark' => $landmark,
  1609. '%species' => $organism->genus . " " . $organism->species,
  1610. ]));
  1611. }
  1612. elseif ($count[0]->num_landmarks > 1) {
  1613. throw new Exception(t("The landmark '%landmark' has more than one entry for this organism (%species) " .
  1614. "Cannot continue", [
  1615. '%landmark' => $landmark,
  1616. '%species' => $organism->genus . " " . $organism->species,
  1617. ]));
  1618. }
  1619. }
  1620. if ($count[0]->num_landmarks > 1) {
  1621. throw new Exception(t("The landmark '%landmark' is not unique for this organism. " .
  1622. "The features cannot be associated", ['%landmark' => $landmark]));
  1623. }
  1624. }
  1625. // Add or update the feature and all properties.
  1626. if ($update or $refresh or $add_only) {
  1627. // Add/update the feature.
  1628. $feature = $this->loadFeature($feature_organism, $analysis_id, $cvterm,
  1629. $attr_uniquename, $attr_name, $residues, $attr_is_analysis,
  1630. $attr_is_obsolete, $add_only, $score);
  1631. if ($feature) {
  1632. // Add a record for this feature to the tripal_gff_temp table for
  1633. // later lookup.
  1634. $values = [
  1635. 'feature_id' => $feature->getID(),
  1636. 'organism_id' => $feature->getValue('organism_id'),
  1637. 'type_name' => $type,
  1638. 'uniquename' => $feature->getValue('uniquename'),
  1639. ];
  1640. // make sure this record doesn't already exist in our temp table
  1641. $results = chado_select_record('tripal_gff_temp', ['*'], $values);
  1642. if (count($results) == 0) {
  1643. $result = chado_insert_record('tripal_gff_temp', $values);
  1644. if (!$result) {
  1645. throw new Exception(t("Cound not save record in temporary table, Cannot continue.", []));
  1646. }
  1647. }
  1648. // Add/update the featureloc if the landmark and the ID are not the
  1649. // same if they are the same then this entry in the GFF is probably
  1650. // a landmark identifier.
  1651. if (strcmp($landmark, $attr_uniquename) != 0) {
  1652. $this->loadFeatureLoc($feature, $organism,
  1653. $landmark, $fmin, $fmax, $strand, $phase, $attr_fmin_partial,
  1654. $attr_fmax_partial, $attr_residue_info, $attr_locgroup);
  1655. }
  1656. // Add any aliases for this feature.
  1657. if (array_key_exists('Alias', $tags)) {
  1658. $this->loadAlias($feature, $tags['Alias']);
  1659. }
  1660. // Add any dbxrefs for this feature.
  1661. if (array_key_exists('Dbxref', $tags)) {
  1662. $this->loadDbxref($feature, $tags['Dbxref']);
  1663. }
  1664. // Add any ontology terms for this feature.
  1665. if (array_key_exists('Ontology_term', $tags)) {
  1666. $this->loadOntology($feature, $tags['Ontology_term']);
  1667. }
  1668. // Add parent relationships.
  1669. if (array_key_exists('Parent', $tags)) {
  1670. $this->loadParents($feature, $cvterm, $tags['Parent'],
  1671. $feature_organism->organism_id, $strand, $phase, $fmin, $fmax);
  1672. }
  1673. // Add target relationships.
  1674. if (array_key_exists('Target', $tags)) {
  1675. $this->loadTarget($feature, $tags, $target_organism_id, $target_type, $create_target, $attr_locgroup);
  1676. }
  1677. // Add gap information. This goes in simply as a property.
  1678. if (array_key_exists('Gap', $tags)) {
  1679. foreach ($tags['Gap'] as $value) {
  1680. $this->loadProperty($feature, 'Gap', $value);
  1681. }
  1682. }
  1683. // Add notes. This goes in simply as a property.
  1684. if (array_key_exists('Note', $tags)) {
  1685. foreach ($tags['Note'] as $value) {
  1686. $this->loadProperty($feature, 'Note', $value);
  1687. }
  1688. }
  1689. // Add the Derives_from relationship (e.g. polycistronic genes).
  1690. if (array_key_exists('Derives_from', $tags)) {
  1691. $this->loadDerivesFrom($feature, $cvterm, $tags['Derives_from'][0],
  1692. $feature_organism, $fmin, $fmax);
  1693. }
  1694. // Add in the GFF3_source dbxref so that GBrowse can find the feature
  1695. // using the source column.
  1696. $source_ref = ['GFF_source:' . $source];
  1697. $this->loadDbxref($feature, $source_ref);
  1698. // Add any additional attributes.
  1699. if ($attr_others) {
  1700. foreach ($attr_others as $tag_name => $values) {
  1701. foreach ($values as $value) {
  1702. $this->loadProperty($feature, $tag_name, $value);
  1703. }
  1704. }
  1705. }
  1706. }
  1707. }
  1708. }
  1709. // Do some last bit of processing.
  1710. if (!$remove) {
  1711. // First, add any protein sequences if needed.
  1712. $sql = "SELECT feature_id FROM {tripal_gffcds_temp} LIMIT 1 OFFSET 1";
  1713. $has_cds = chado_query($sql)->fetchField();
  1714. if ($has_cds) {
  1715. $this->logMessage("\nAdding protein sequences if CDS exist and no proteins in GFF...");
  1716. $sql = "
  1717. SELECT F.feature_id, F.name, F.uniquename, TGCT.strand,
  1718. CVT.cvterm_id, CVT.name as feature_type,
  1719. min(TGCT.fmin) as fmin, max(TGCT.fmax) as fmax,
  1720. TGPT.feature_id as protein_id, TGPT.fmin as protein_fmin,
  1721. TGPT.fmax as protein_fmax, FLM.uniquename as landmark
  1722. FROM {tripal_gffcds_temp} TGCT
  1723. INNER JOIN {feature} F on F.feature_id = TGCT.parent_id
  1724. INNER JOIN {cvterm} CVT on CVT.cvterm_id = F.type_id
  1725. INNER JOIN {featureloc} L on F.feature_id = L.feature_id
  1726. INNER JOIN {feature} FLM on L.srcfeature_id = FLM.feature_id
  1727. LEFT JOIN {tripal_gffprotein_temp} TGPT on TGPT.parent_id = F.feature_id
  1728. GROUP BY F.feature_id, F.name, F.uniquename, CVT.cvterm_id, CVT.name,
  1729. TGPT.feature_id, TGPT.fmin, TGPT.fmax, TGCT.strand, FLM.uniquename
  1730. ";
  1731. $results = chado_query($sql);
  1732. $protein_cvterm = $this->getCvterm('polypeptide');
  1733. while ($result = $results->fetchObject()) {
  1734. // If a protein exists with this same parent then don't add a new
  1735. // protein.
  1736. if (!$result->protein_id) {
  1737. // Get details about this protein
  1738. if ($re_mrna and $re_protein) {
  1739. // We use a regex to generate protein name from mRNA name
  1740. $uname = preg_replace("/$re_mrna/", $re_protein, $result->uniquename);
  1741. $name = $result->name;
  1742. }
  1743. else {
  1744. // No regex, use the default '-protein' suffix
  1745. $uname = $result->uniquename . '-protein';
  1746. $name = $result->name;
  1747. }
  1748. $values = [
  1749. 'parent_id' => $result->feature_id,
  1750. 'fmin' => $result->fmin,
  1751. ];
  1752. $min_phase = chado_select_record('tripal_gffcds_temp', ['phase'], $values);
  1753. $values = [
  1754. 'parent_id' => $result->feature_id,
  1755. 'fmax' => $result->fmax,
  1756. ];
  1757. $max_phase = chado_select_record('tripal_gffcds_temp', ['phase'], $values);
  1758. $pfmin = $result->fmin;
  1759. $pfmax = $result->fmax;
  1760. if ($result->strand == '-1') {
  1761. $pfmax -= $max_phase[0]->phase;
  1762. }
  1763. else {
  1764. $pfmin += $min_phase[0]->phase;
  1765. }
  1766. if ($skip_protein == 0) {
  1767. // Add the new protein record.
  1768. $feature = $this->loadFeature($organism, $analysis_id,
  1769. $protein_cvterm, $uname, $name, '', 'f', 'f', 1, 0);
  1770. // Add the derives_from relationship.
  1771. $cvterm = $this->getCvterm($result->feature_type);
  1772. $this->loadDerivesFrom($feature, $cvterm,
  1773. $result->uniquename, $organism, $pfmin, $pfmax);
  1774. // Add the featureloc record. Set the start of the protein to
  1775. // be the start of the coding sequence minus the phase.
  1776. $this->loadFeatureLoc($feature, $organism, $result->landmark,
  1777. $pfmin, $pfmax, $result->strand, '', 'f', 'f', '', 0);
  1778. }
  1779. }
  1780. }
  1781. }
  1782. $this->logMessage("Setting ranks of children...");
  1783. // Get features in a relationship that are also children of an alignment.
  1784. $sql = "
  1785. SELECT DISTINCT F.feature_id, F.organism_id, F.type_id,
  1786. F.uniquename, FL.strand
  1787. FROM {tripal_gff_temp} TGT
  1788. INNER JOIN {feature} F ON TGT.feature_id = F.feature_id
  1789. INNER JOIN {feature_relationship} FR ON FR.object_id = TGT.feature_id
  1790. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = FR.type_id
  1791. INNER JOIN {featureloc} FL ON FL.feature_id = F.feature_id
  1792. WHERE CVT.name = 'part_of'
  1793. ";
  1794. $parents = chado_query($sql);
  1795. // Build and prepare the SQL for selecting the children relationship.
  1796. $sel_gffchildren_sql = "
  1797. SELECT DISTINCT FR.feature_relationship_id, FL.fmin, FR.rank
  1798. FROM {feature_relationship} FR
  1799. INNER JOIN {featureloc} FL on FL.feature_id = FR.subject_id
  1800. INNER JOIN {cvterm} CVT on CVT.cvterm_id = FR.type_id
  1801. WHERE FR.object_id = :feature_id AND CVT.name = 'part_of'
  1802. ORDER BY FL.fmin ASC
  1803. ";
  1804. // Now set the rank of any parent/child relationships. The order is based
  1805. // on the fmin. The start rank is 1. This allows features with other
  1806. // relationships to be '0' (the default), and doesn't interfer with the
  1807. // ordering defined here.
  1808. $num_recs = $parents->rowCount();
  1809. $i = 1;
  1810. while ($parent = $parents->fetchObject()) {
  1811. // get the children
  1812. $result = chado_query($sel_gffchildren_sql, [':feature_id' => $parent->feature_id]);
  1813. // build an array of the children
  1814. $children = [];
  1815. while ($child = $result->fetchObject()) {
  1816. $children[] = $child;
  1817. }
  1818. // the children list comes sorted in ascending fmin
  1819. // but if the parent is on the reverse strand we need to
  1820. // reverse the order of the children.
  1821. if ($parent->strand == -1) {
  1822. arsort($children);
  1823. }
  1824. // first set the ranks to a negative number so that we don't
  1825. // get a duplicate error message when we try to change any of them
  1826. $rank = -1;
  1827. foreach ($children as $child) {
  1828. $match = ['feature_relationship_id' => $child->feature_relationship_id];
  1829. $values = ['rank' => $rank];
  1830. chado_update_record('feature_relationship', $match, $values);
  1831. $rank--;
  1832. }
  1833. // now set the rank correctly. The rank should start at 0.
  1834. $rank = 0;
  1835. foreach ($children as $child) {
  1836. $match = ['feature_relationship_id' => $child->feature_relationship_id];
  1837. $values = ['rank' => $rank];
  1838. chado_update_record('feature_relationship', $match, $values);
  1839. $rank++;
  1840. }
  1841. $i++;
  1842. }
  1843. }
  1844. return 1;
  1845. }
  1846. /**
  1847. * Load a controlled vocabulary term.
  1848. *
  1849. * This method first checks if the term has already been loaded in the
  1850. * feature_cvterm_lookup array, which helps a lot with performance.
  1851. *
  1852. * @param $type
  1853. * @param $cv_id
  1854. *
  1855. * @ingroup gff3_loader
  1856. */
  1857. private function getCvtermID($type, $cv_id = NULL, $is_prop_type = FALSE) {
  1858. if (!isset($cv_id)) {
  1859. $cv_id = $this->sequence_cv_id;
  1860. }
  1861. if ($is_prop_type and array_key_exists($type, $this->featureprop_cvterm_lookup)) {
  1862. return $this->featureprop_cvterm_lookup[$type];
  1863. }
  1864. elseif (array_key_exists($type, $this->feature_cvterm_lookup)) {
  1865. return $this->feature_cvterm_lookup[$type];
  1866. }
  1867. $sel_cvterm_sql = "
  1868. SELECT CVT.cvterm_id
  1869. FROM {cvterm} CVT
  1870. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  1871. WHERE CVT.cv_id = {$cv_id} and
  1872. (lower(CVT.name) = lower(:name) or lower(CVTS.synonym) = lower(:synonym))
  1873. ";
  1874. $result = chado_query($sel_cvterm_sql, [
  1875. ':name' => $type,
  1876. ':synonym' => $type,
  1877. ]);
  1878. $cvterm = $result->fetchObject() ?? NULL;
  1879. if ($cvterm) {
  1880. $cvterm = chado_get_cvterm(array('cvterm_id' => $cvterm->cvterm_id)) ?? NULL;
  1881. }
  1882. if ($is_prop_type) {
  1883. $this->featureprop_cvterm_lookup[$cvterm->name] = $cvterm->cvterm_id;
  1884. $this->featureprop_cvterm_lookup[$type] = $cvterm->cvterm_id;
  1885. }
  1886. else {
  1887. $this->feature_cvterm_lookup[$cvterm->name] = $cvterm->cvterm_id;
  1888. $this->feature_cvterm_lookup[$type] = $cvterm->cvterm_id;
  1889. // If the cvterm name does not match the name provided then set a mapping.
  1890. if ($cvterm->name != $type) {
  1891. $this->feature_cvterm_aliases[$type] = $cvterm->name;
  1892. }
  1893. }
  1894. return $cvterm->cvterm_id;
  1895. }
  1896. /**
  1897. * Retrieves a ChadoRecord object for the landmark feature.
  1898. *
  1899. * @param $landmark_name
  1900. * The name of the landmark to get
  1901. * @param $landmark_type
  1902. * A ChadoRecord object for the type of landmark.
  1903. * @param $skip_on_missing
  1904. * If the landmark cannot be found and this arugment is FALSE then
  1905. * an error will be thrown. If TRUE then no error is thrown.
  1906. *
  1907. * @return
  1908. * A feature ChadoRecord object or NULL if the landmark is missing and
  1909. * $skip_on_missing is TRUE.
  1910. */
  1911. private function getLandmark($landmark_name, $landmark_type = NULL, $skip_on_missing = FALSE) {
  1912. // Before performing a database query check to see if
  1913. // this landmark is already in our lookup list.
  1914. if (array_key_exists($landmark_name, $this->landmarks)) {
  1915. return $this->landmarks[$landmark_name];
  1916. }
  1917. $landmark = new ChadoRecord('feature');
  1918. $landmark->setValues([
  1919. 'organism_id' => $this->organism_id,
  1920. 'uniquename' => $landmark_name,
  1921. ]);
  1922. if ($landmark_type) {
  1923. $landmark->setValue('type_id', $landmark_type->getValue('cvterm_id'));
  1924. }
  1925. $num_found = $landmark->find();
  1926. if ($num_found == 0) {
  1927. if ($skip_on_missing == TRUE) {
  1928. return NULL;
  1929. }
  1930. throw new Exception(t("The landmark '%landmark' cannot be found for this organism (%species) " .
  1931. "Please add the landmark and then retry the import of this GFF3 " .
  1932. "file", [
  1933. '%landmark' => $landmark_name,
  1934. '%species' => $this->organism->getValues('genus') . " " . $this->organism->getValues('species'),
  1935. ]));
  1936. }
  1937. if ($num_found > 1) {
  1938. 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." .
  1939. "Cannot continue", [
  1940. '%landmark' => $landmark_name,
  1941. '%species' => $this->organism->getValues('genus') . " " . $this->organism->getValues('species'),
  1942. ]));
  1943. }
  1944. // The landmark was found, remember it
  1945. $this->landmarks[$landmark_name] = $landmark;
  1946. return $landmark;
  1947. }
  1948. /**
  1949. * Retrives the organism ID that matches the provided string.
  1950. *
  1951. * The organism string is expected to be in the format genus:species
  1952. * or just the full name separated by spaces.
  1953. */
  1954. private function getOrganism($org_string) {
  1955. // Before performing a database query check to see if
  1956. // this organism is already in our lookup list.
  1957. if (array_key_exists($org_string, $this->organism_lookup)) {
  1958. return $this->organism_lookup[$org_string];
  1959. }
  1960. // See if the genus and species are spearated by a colon.
  1961. $org_matches = [];
  1962. if (preg_match('/^(.*?):(.*?)$/', $org_string, $org_matches)) {
  1963. $values = [
  1964. 'genus' => $org_matches[1],
  1965. 'species' => $org_matches[2],
  1966. ];
  1967. }
  1968. // See if the genus, species and infraspecific name are present.
  1969. elseif (preg_match('/^(.*?)\s+(.*?)\s+(.*)$/', $org_string, $org_matches)) {
  1970. $values = [
  1971. 'genus' => $org_matches[1],
  1972. 'species' => $org_matches[2],
  1973. 'infraspecific_name' => $org_matches[3],
  1974. ];
  1975. }
  1976. // See if just the genus ans species are present.
  1977. elseif (preg_match('/^(.*?)\s+(.*?)$/', $org_string, $org_matches)) {
  1978. $values = [
  1979. 'genus' => $org_matches[1],
  1980. 'species' => $org_matches[2],
  1981. ];
  1982. }
  1983. else {
  1984. 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]));
  1985. }
  1986. // Get the organism record and add it to our lookup list for next time.
  1987. $organism = new ChadoRecord('organism');
  1988. $organism->setValues($values);
  1989. $num_found = $organism->find();
  1990. if ($num_found == 0) {
  1991. throw new Exception(t("Cannot find the specified organism, '%organism', for this GFF3 file.", ['%organism' => $org_string]));
  1992. }
  1993. $this->organism_lookup[$org_string] = $organism;
  1994. return $organism;
  1995. }
  1996. /**
  1997. * Retrieves the residues for a given feature.
  1998. *
  1999. */
  2000. private function getResidues($feature, $is_landmark = FALSE) {
  2001. return '';
  2002. }
  2003. /**
  2004. * Determines the name for a feature using the ID and name attributes.
  2005. *
  2006. * @param $feature_attrs
  2007. * The associative array of attributes for the feature.
  2008. *
  2009. * @param $type
  2010. * The type of feature.
  2011. *
  2012. * @return array
  2013. * An associative array with 'uniquename' and 'name' keys.
  2014. */
  2015. private function getFeatureName($attrs, $type, $landmark_name, $fmin, $fmax) {
  2016. // To ensure a name is unique we may need to use the date.
  2017. $uniquename = '';
  2018. $name = '';
  2019. // If there is no ID or name then try to create a name and ID.
  2020. if (!array_key_exists('ID', $attrs) and !array_key_exists('name', $attrs)) {
  2021. // Check if an alternate ID field is suggested, if so, then use
  2022. // that for the name.
  2023. if (array_key_exists($this->alt_id_attr, $attrs)) {
  2024. $uniquename = $attrs[$this->alt_id_attr][0];
  2025. $name = $uniquename;
  2026. }
  2027. // If the row has a parent then generate a unqiue ID
  2028. elseif (array_key_exists('Parent', $attrs)) {
  2029. $uniquename = md5($attrs['Parent'][0] . "-" . $type . "-" .
  2030. $landmark_name . ":" . ($fmin + 1) . ".." . $fmax);
  2031. $name = $attrs['Parent'][0] . "-" . $type;
  2032. }
  2033. // Generate a unique name based on the date, type and location
  2034. // and set the name to simply be the type.
  2035. else {
  2036. $uniquename = md5($type . "-" . $landmark_name . ":" . ($fmin + 1) . ".." . $fmax);
  2037. $name = $type . "-" . $landmark_name;
  2038. }
  2039. }
  2040. elseif (!array_key_exists('Name', $attrs)) {
  2041. $uniquename = $attrs['ID'][0];
  2042. $name = $attrs['ID'][0];
  2043. }
  2044. elseif (!array_key_exists('ID', $attrs)) {
  2045. $uniquename = $attrs['Name'][0];
  2046. $name = $attrs['Name'][0];
  2047. }
  2048. else {
  2049. $uniquename = $attrs['ID'][0];
  2050. $name = $attrs['Name'][0];
  2051. }
  2052. // Does this uniquename already exist? This can happen for subfeatures
  2053. // (e.g. CDS features) that have multiple components but are really
  2054. // all the same thing.
  2055. if (array_key_exists($uniquename, $this->features)) {
  2056. if (array_key_exists('Parent', $attrs)) {
  2057. // Iterate through the list of similar IDs and see how many we have
  2058. // then add a numeric suffix.
  2059. $i = 2;
  2060. while (array_key_exists($uniquename . "_" . $i, $this->features)) {
  2061. $i++;
  2062. }
  2063. $uniquename = $uniquename . "_" . $i;
  2064. }
  2065. else {
  2066. throw new Exception(t("A feature with the same ID exists multiple times: !uname", ['!uname' => $uniquename]));
  2067. }
  2068. }
  2069. return [
  2070. 'name' => $name,
  2071. 'uniquename' => $uniquename,
  2072. ];
  2073. }
  2074. /**
  2075. * Load the derives from attribute for a gff3 feature
  2076. *
  2077. * @param $feature
  2078. * @param $subject
  2079. * @param $organism
  2080. *
  2081. * @ingroup gff3_loader
  2082. */
  2083. private function loadDerivesFrom($feature, $cvterm, $object,
  2084. $organism, $fmin, $fmax) {
  2085. $type = $cvterm->name;
  2086. $derivesfrom_term = $this->getCvterm('derives_from');
  2087. // First look for the object feature in the temp table to get it's type.
  2088. $values = [
  2089. 'organism_id' => $organism->organism_id,
  2090. 'uniquename' => $object,
  2091. ];
  2092. $result = chado_select_record('tripal_gff_temp', ['type_name'], $values);
  2093. $type_id = NULL;
  2094. if (count($result) > 0) {
  2095. $type_id = $this->getCvterm($result[0]->type_name)->cvterm_id ?? NULL;
  2096. }
  2097. // If the object wasn't in the temp table then look for it in the
  2098. // feature table and get it's type.
  2099. if (!$type_id) {
  2100. $result = chado_select_record('feature', ['type_id'], $values);
  2101. if (count($result) > 1) {
  2102. $this->logMessage("Cannot find feature type for, '!subject' , in 'derives_from' relationship. Multiple matching features exist with this uniquename.",
  2103. ['!subject' => $object], TRIPAL_WARNING);
  2104. return;
  2105. }
  2106. else {
  2107. if (count($result) == 0) {
  2108. $this->logMessage("Cannot find feature type for, '!subject' , in 'derives_from' relationship.",
  2109. ['!subject' => $object], TRIPAL_WARNING);
  2110. return '';
  2111. }
  2112. else {
  2113. $type_id = $result->type_id;
  2114. }
  2115. }
  2116. }
  2117. // Get the object feature.
  2118. $match = [
  2119. 'organism_id' => $organism->organism_id,
  2120. 'uniquename' => $object,
  2121. 'type_id' => $type_id,
  2122. ];
  2123. $ofeature = chado_select_record('feature', ['feature_id'], $match);
  2124. if (count($ofeature) == 0) {
  2125. $this->logMessage("Could not add 'Derives_from' relationship " .
  2126. "for %uniquename and %subject. Subject feature, '%subject', " .
  2127. "cannot be found.", [
  2128. '%uniquename' => $feature->getValue('uniquename'),
  2129. '%subject' => $subject,
  2130. ], TRIPAL_ERROR);
  2131. return;
  2132. }
  2133. // If this feature is a protein then add it to the tripal_gffprotein_temp.
  2134. if ($type == 'protein' or $type == 'polypeptide') {
  2135. $values = [
  2136. 'feature_id' => $feature->getID(),
  2137. 'parent_id' => $ofeature[0]->feature_id,
  2138. 'fmin' => $fmin,
  2139. 'fmax' => $fmax,
  2140. ];
  2141. $result = chado_insert_record('tripal_gffprotein_temp', $values);
  2142. if (!$result) {
  2143. throw new Exception(t("Cound not save record in temporary protein table, Cannot continue.", []));
  2144. }
  2145. }
  2146. // Now check to see if the relationship already exists. If it does
  2147. // then just return.
  2148. $values = [
  2149. 'object_id' => $ofeature[0]->feature_id,
  2150. 'subject_id' => $feature->getID(),
  2151. 'type_id' => $derivesfrom_term->cvterm_id,
  2152. 'rank' => 0,
  2153. ];
  2154. $rel = chado_select_record('feature_relationship', ['*'], $values);
  2155. if (count($rel) > 0) {
  2156. return;
  2157. }
  2158. // finally insert the relationship if it doesn't exist
  2159. $ret = chado_insert_record('feature_relationship', $values, array(
  2160. 'skip_validation' => TRUE,
  2161. ));
  2162. if (!$ret) {
  2163. $this->logMessage("Could not add 'Derives_from' relationship for :uniquename and :subject.",
  2164. [
  2165. ':uniquename' => $feature->getValue('uniquename'),
  2166. ':subject' => $subject,
  2167. ], TRIPAL_WARNING);
  2168. }
  2169. }
  2170. /**
  2171. * Load the parents for a gff3 feature
  2172. *
  2173. * @param $feature
  2174. * @param $cvterm
  2175. * @param $parents
  2176. * @param $organism_id
  2177. * @param $fmin
  2178. *
  2179. * @ingroup gff3_loader
  2180. */
  2181. private function loadParents($feature, $cvterm, $parents,
  2182. $organism_id, $strand, $phase, $fmin, $fmax) {
  2183. $uname = $feature->getValue('uniquename');
  2184. $type = $cvterm->name;
  2185. $rel_type = 'part_of';
  2186. $relcvterm = $this->getCvterm($rel_type);
  2187. if (!$relcvterm) {
  2188. 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."));
  2189. }
  2190. // Iterate through the parents in the list.
  2191. foreach ($parents as $parent) {
  2192. // Get the parent cvterm.
  2193. $values = [
  2194. 'organism_id' => $organism_id,
  2195. 'uniquename' => $parent,
  2196. ];
  2197. $result = chado_select_record('tripal_gff_temp', ['type_name'], $values);
  2198. if (count($result) == 0) {
  2199. $this->logMessage("Cannot find parent: %parent.", ['%parent' => $parent], TRIPAL_WARNING);
  2200. return '';
  2201. }
  2202. $parent_type = $result[0]->type_name;
  2203. // try to find the parent
  2204. $parentcvterm = $this->getCvterm($parent_type);
  2205. $values = [
  2206. 'organism_id' => $organism_id,
  2207. 'uniquename' => $parent,
  2208. 'type_id' => $parentcvterm->cvterm_id,
  2209. ];
  2210. $result = chado_select_record('feature', ['feature_id'], $values);
  2211. $parent_feature = $result[0];
  2212. // if the parent exists then add the relationship otherwise print error and skip
  2213. if ($parent_feature) {
  2214. // check to see if the relationship already exists
  2215. $values = [
  2216. 'object_id' => $parent_feature->feature_id,
  2217. 'subject_id' => $feature->getID(),
  2218. 'type_id' => $relcvterm->cvterm_id,
  2219. ];
  2220. $rel = chado_select_record('feature_relationship', ['*'], $values);
  2221. if (count($rel) > 0) {
  2222. }
  2223. else {
  2224. // the relationship doesn't already exist, so add it.
  2225. $values = [
  2226. 'subject_id' => $feature->getID(),
  2227. 'object_id' => $parent_feature->feature_id,
  2228. 'type_id' => $relcvterm->cvterm_id,
  2229. ];
  2230. $result = chado_insert_record('feature_relationship', $values, array(
  2231. 'skip_validation' => TRUE,
  2232. ));
  2233. if (!$result) {
  2234. $this->logMessage("Failed to insert feature relationship '$uname' ($type) $rel_type '$parent' ($parent_type).",
  2235. [], TRIPAL_WARNING);
  2236. }
  2237. }
  2238. // If this feature is a CDS and now that we know the parent we can
  2239. // add it to the tripal_gffcds_temp table for later lookup.
  2240. if ($type == 'CDS') {
  2241. $values = [
  2242. 'feature_id' => $feature->getID(),
  2243. 'parent_id' => $parent_feature->feature_id,
  2244. 'fmin' => $fmin,
  2245. 'fmax' => $fmax,
  2246. 'strand' => $strand,
  2247. ];
  2248. if (isset($phase)) {
  2249. $values['phase'] = $phase;
  2250. }
  2251. $result = chado_insert_record('tripal_gffcds_temp', $values, array(
  2252. 'skip_validation' => TRUE,
  2253. ));
  2254. if (!$result) {
  2255. throw new Exception(t("Cound not save record in temporary CDS table, Cannot continue.", []));
  2256. exit;
  2257. }
  2258. }
  2259. }
  2260. else {
  2261. $this->logMessage("Cannot establish relationship '$uname' ($type) $rel_type '$parent' ($parent_type): Cannot find the parent.",
  2262. [], TRIPAL_WARNING);
  2263. }
  2264. }
  2265. }
  2266. /**
  2267. * Load the dbxref attribute for a feature
  2268. *
  2269. * @param $feature
  2270. * @param $dbxrefs
  2271. *
  2272. * @ingroup gff3_loader
  2273. */
  2274. private function loadDbxref($feature, $dbxrefs) {
  2275. // iterate through each of the dbxrefs
  2276. foreach ($dbxrefs as $dbxref) {
  2277. // get the database name from the reference. If it doesn't exist then create one.
  2278. $ref = explode(":", $dbxref);
  2279. $dbname = trim($ref[0]);
  2280. $accession = trim($ref[1]);
  2281. // first look for the database name if it doesn't exist then create one.
  2282. // first check for the fully qualified URI (e.g. DB:<dbname>. If that
  2283. // can't be found then look for the name as is. If it still can't be found
  2284. // the create the database
  2285. $values = ['name' => "DB:$dbname"];
  2286. $db = chado_select_record('db', ['db_id'], $values);
  2287. if (count($db) == 0) {
  2288. $values = ['name' => "$dbname"];
  2289. $db = chado_select_record('db', ['db_id'], $values);
  2290. }
  2291. if (count($db) == 0) {
  2292. $values = [
  2293. 'name' => $dbname,
  2294. 'description' => 'Added automatically by the GFF loader',
  2295. ];
  2296. $success = chado_insert_record('db', $values, array(
  2297. 'skip_validation' => TRUE,
  2298. ));
  2299. if ($success) {
  2300. $values = ['name' => "$dbname"];
  2301. $db = chado_select_record('db', ['db_id'], $values);
  2302. }
  2303. else {
  2304. $this->logMessage("Cannot find or add the database $dbname.", [], TRIPAL_WARNING);
  2305. return 0;
  2306. }
  2307. }
  2308. $db = $db[0];
  2309. // now check to see if the accession exists
  2310. $values = [
  2311. 'accession' => $accession,
  2312. 'db_id' => $db->db_id,
  2313. ];
  2314. $dbxref = chado_select_record('dbxref', ['dbxref_id'], $values);
  2315. // if the accession doesn't exist then we want to add it
  2316. if (sizeof($dbxref) == 0) {
  2317. $values = [
  2318. 'db_id' => $db->db_id,
  2319. 'accession' => $accession,
  2320. 'version' => '',
  2321. ];
  2322. $ret = chado_insert_record('dbxref', $values, array(
  2323. 'skip_validation' => TRUE,
  2324. ));
  2325. $values = [
  2326. 'accession' => $accession,
  2327. 'db_id' => $db->db_id,
  2328. ];
  2329. $dbxref = chado_select_record('dbxref', ['dbxref_id'], $values);
  2330. }
  2331. $dbxref = $dbxref[0];
  2332. // check to see if this feature dbxref already exists
  2333. $values = [
  2334. 'dbxref_id' => $dbxref->dbxref_id,
  2335. 'feature_id' => $feature->getID(),
  2336. ];
  2337. $fdbx = chado_select_record('feature_dbxref', ['feature_dbxref_id'], $values);
  2338. // now associate this feature with the database reference if it doesn't
  2339. // already exist
  2340. if (sizeof($fdbx) == 0) {
  2341. $values = [
  2342. 'dbxref_id' => $dbxref->dbxref_id,
  2343. 'feature_id' => $feature->getID(),
  2344. ];
  2345. $success = chado_insert_record('feature_dbxref', $values, array(
  2346. 'skip_validation' => TRUE,
  2347. ));
  2348. if (!$success) {
  2349. $this->logMessage("Failed to insert Dbxref: $dbname:$accession.", [], TRIPAL_WARNING);
  2350. return 0;
  2351. }
  2352. }
  2353. }
  2354. return 1;
  2355. }
  2356. /**
  2357. * Load the cvterms for a feature.
  2358. *
  2359. * Assumes there is a dbxref.accession matching a cvterm.name
  2360. *
  2361. * @param $feature
  2362. * @param $dbxrefs
  2363. *
  2364. * @ingroup gff3_loader
  2365. */
  2366. private function loadOntology($feature, $dbxrefs) {
  2367. // iterate through each of the dbxrefs
  2368. foreach ($dbxrefs as $dbxref) {
  2369. // get the database name from the reference. If it doesn't exist then create one.
  2370. $ref = explode(":", $dbxref);
  2371. $dbname = trim($ref[0]);
  2372. $accession = trim($ref[1]);
  2373. // first look for the database name
  2374. $db = chado_select_record('db', ['db_id'], ['name' => "DB:$dbname"]);
  2375. if (sizeof($db) == 0) {
  2376. // now look for the name without the 'DB:' prefix.
  2377. $db = chado_select_record('db', ['db_id'], ['name' => "$dbname"]);
  2378. if (sizeof($db) == 0) {
  2379. $this->logMessage("Database, $dbname, is not present. Cannot associate term: $dbname:$accession.", [], TRIPAL_WARNING);
  2380. continue;
  2381. }
  2382. }
  2383. $db = $db[0];
  2384. // now check to see if the accession exists
  2385. $dbxref = chado_select_record('dbxref', ['dbxref_id'],
  2386. ['accession' => $accession, 'db_id' => $db->db_id]);
  2387. if (sizeof($dbxref) == 0) {
  2388. $this->logMessage("Accession, $accession is missing for reference: $dbname:$accession.", [], TRIPAL_WARNING);
  2389. continue;
  2390. }
  2391. $dbxref = $dbxref[0];
  2392. // now check to see if the cvterm exists
  2393. $cvterm = chado_select_record('cvterm', ['cvterm_id'], [
  2394. 'dbxref_id' => $dbxref->dbxref_id,
  2395. ]);
  2396. // if it doesn't exist in the cvterm table, look for an alternate id
  2397. if (sizeof($cvterm) == 0) {
  2398. $cvterm = chado_select_record('cvterm_dbxref', ['cvterm_id'], [
  2399. 'dbxref_id' => $dbxref->dbxref_id,
  2400. ]);
  2401. if (sizeof($cvterm) == 0) {
  2402. $this->logMessage("CV Term is missing for reference: $dbname:$accession.", [], TRIPAL_WARNING);
  2403. continue;
  2404. }
  2405. }
  2406. $cvterm = $cvterm[0];
  2407. // check to see if this feature cvterm already exists
  2408. $fcvt = chado_select_record('feature_cvterm', ['feature_cvterm_id'],
  2409. [
  2410. 'cvterm_id' => $cvterm->cvterm_id,
  2411. 'feature_id' => $feature->getID(),
  2412. ]);
  2413. // now associate this feature with the cvterm if it doesn't already exist
  2414. if (sizeof($fcvt) == 0) {
  2415. $values = [
  2416. 'cvterm_id' => $cvterm->cvterm_id,
  2417. 'feature_id' => $feature->getID(),
  2418. 'pub_id' => [
  2419. 'uniquename' => 'null',
  2420. ],
  2421. ];
  2422. $success = chado_insert_record('feature_cvterm', $values, array(
  2423. 'skip_validation' => TRUE,
  2424. ));
  2425. if (!$success) {
  2426. $this->logMessage("Failed to insert ontology term: $dbname:$accession.", [], TRIPAL_WARNING);
  2427. continue;
  2428. }
  2429. }
  2430. }
  2431. }
  2432. /**
  2433. * Load any aliases for a feature
  2434. *
  2435. * @param $feature
  2436. * @param $aliases
  2437. *
  2438. * @ingroup gff3_loader
  2439. */
  2440. private function loadAlias($feature, $aliases) {
  2441. // make sure we have a 'synonym_type' vocabulary
  2442. $select = ['name' => 'synonym_type'];
  2443. $results = chado_select_record('cv', ['*'], $select);
  2444. if (count($results) == 0) {
  2445. // insert the 'synonym_type' vocabulary
  2446. $values = [
  2447. 'name' => 'synonym_type',
  2448. 'definition' => 'vocabulary for synonym types',
  2449. ];
  2450. $success = chado_insert_record('cv', $values, array(
  2451. 'skip_validation' => TRUE,
  2452. ));
  2453. if (!$success) {
  2454. $this->logMessage("Failed to add the synonyms type vocabulary.", [], TRIPAL_WARNING);
  2455. return 0;
  2456. }
  2457. // now that we've added the cv we need to get the record
  2458. $results = chado_select_record('cv', ['*'], $select);
  2459. if (count($results) > 0) {
  2460. $syncv = $results[0];
  2461. }
  2462. }
  2463. else {
  2464. $syncv = $results[0];
  2465. }
  2466. // get the 'exact' cvterm, which is the type of synonym we're adding
  2467. $select = [
  2468. 'name' => 'exact',
  2469. 'cv_id' => [
  2470. 'name' => 'synonym_type',
  2471. ],
  2472. ];
  2473. $result = chado_select_record('cvterm', ['*'], $select);
  2474. if (count($result) == 0) {
  2475. $term = [
  2476. 'name' => 'exact',
  2477. 'id' => "synonym_type:exact",
  2478. 'definition' => '',
  2479. 'is_obsolete' => 0,
  2480. 'cv_name' => $syncv->name,
  2481. 'is_relationship' => FALSE,
  2482. ];
  2483. $syntype = chado_insert_cvterm($term, ['update_existing' => TRUE]);
  2484. if (!$syntype) {
  2485. $this->logMessage("Cannot add synonym type: internal:$type.", [], TRIPAL_WARNING);
  2486. return 0;
  2487. }
  2488. }
  2489. else {
  2490. $syntype = $result[0];
  2491. }
  2492. // iterate through all of the aliases and add each one
  2493. foreach ($aliases as $alias) {
  2494. // check to see if the alias already exists in the synonym table
  2495. // if not, then add it
  2496. $select = [
  2497. 'name' => $alias,
  2498. 'type_id' => $syntype->cvterm_id,
  2499. ];
  2500. $result = chado_select_record('synonym', ['*'], $select);
  2501. if (count($result) == 0) {
  2502. $values = [
  2503. 'name' => $alias,
  2504. 'type_id' => $syntype->cvterm_id,
  2505. 'synonym_sgml' => '',
  2506. ];
  2507. $success = chado_insert_record('synonym', $values, array(
  2508. 'skip_validation' => TRUE,
  2509. ));
  2510. if (!$success) {
  2511. $this->logMessage("Cannot add alias $alias to synonym table.", [], TRIPAL_WARNING);
  2512. return 0;
  2513. }
  2514. $result = chado_select_record('synonym', ['*'], $select);
  2515. $synonym = $result[0];
  2516. }
  2517. else {
  2518. $synonym = $result[0];
  2519. }
  2520. // check to see if we have a NULL publication in the pub table. If not,
  2521. // then add one.
  2522. $select = ['uniquename' => 'null'];
  2523. $result = chado_select_record('pub', ['*'], $select);
  2524. if (count($result) == 0) {
  2525. $pub_sql = "
  2526. INSERT INTO {pub} (uniquename,type_id)
  2527. VALUES (:uname,
  2528. (SELECT cvterm_id
  2529. FROM {cvterm} CVT
  2530. INNER JOIN {dbxref} DBX ON DBX.dbxref_id = CVT.dbxref_id
  2531. INNER JOIN {db} DB ON DB.db_id = DBX.db_id
  2532. WHERE CVT.name = :type_id))
  2533. ";
  2534. $status = chado_query($psql);
  2535. if (!$status) {
  2536. $this->logMessage("Cannot prepare statement 'ins_pub_uniquename_typeid.", [], TRIPAL_WARNING);
  2537. return 0;
  2538. }
  2539. // insert the null pub
  2540. $result = chado_query($pub_sql, [
  2541. ':uname' => 'null',
  2542. ':type_id' => 'null',
  2543. ])->fetchObject();
  2544. if (!$result) {
  2545. $this->logMessage("Cannot add null publication needed for setup of alias.", [], TRIPAL_WARNING);
  2546. return 0;
  2547. }
  2548. $result = chado_select_record('pub', ['*'], $select);
  2549. $pub = $result[0];
  2550. }
  2551. else {
  2552. $pub = $result[0];
  2553. }
  2554. // check to see if the synonym exists in the feature_synonym table
  2555. // if not, then add it.
  2556. $values = [
  2557. 'synonym_id' => $synonym->synonym_id,
  2558. 'feature_id' => $feature->getID(),
  2559. 'pub_id' => $pub->pub_id,
  2560. ];
  2561. $columns = ['feature_synonym_id'];
  2562. $result = chado_select_record('feature_synonym', $columns, $values);
  2563. if (count($result) == 0) {
  2564. $values = [
  2565. 'synonym_id' => $synonym->synonym_id,
  2566. 'feature_id' => $feature->getID(),
  2567. 'pub_id' => $pub->pub_id,
  2568. ];
  2569. $success = chado_insert_record('feature_synonym', $values, array(
  2570. 'skip_validation' => TRUE,
  2571. ));
  2572. if (!$success) {
  2573. $this->logMessage("Cannot add alias $alias to feature synonym table.", [], TRIPAL_WARNING);
  2574. return 0;
  2575. }
  2576. }
  2577. }
  2578. return 1;
  2579. }
  2580. /**
  2581. * Create the feature record & link it to it's analysis
  2582. *
  2583. * @param $organism
  2584. * @param $analysis_id
  2585. * @param $cvterm
  2586. * @param $uniquename
  2587. * @param $name
  2588. * @param $residues
  2589. * @param $is_analysis
  2590. * @param $is_obsolete
  2591. * @param $add_only
  2592. * @param $score
  2593. *
  2594. * @ingroup gff3_loader
  2595. */
  2596. private function loadFeature($organism, $analysis, $cvterm, $uniquename,
  2597. $name, $residues, $is_analysis = 'f', $is_obsolete = 'f', $add_only, $score) {
  2598. if (strcmp($is_obsolete, 'f') == 0 or $is_obsolete == 0) {
  2599. $is_obsolete = 'FALSE';
  2600. }
  2601. if (strcmp($is_obsolete, 't') == 0 or $is_obsolete == 1) {
  2602. $is_obsolete = 'TRUE';
  2603. }
  2604. if (strcmp($is_analysis, 'f') == 0 or $is_analysis == 0) {
  2605. $is_analysis = 'FALSE';
  2606. }
  2607. if (strcmp($is_analysis, 't') == 0 or $is_analysis == 1) {
  2608. $is_analysis = 'TRUE';
  2609. }
  2610. // Check to see if the feature already exists.
  2611. $feature = new ChadoRecord('feature');
  2612. $feature->setValues([
  2613. 'organism_id' => $organism->getValue('organism_id'),
  2614. 'uniquename' => $uniquename,
  2615. 'type_id' => $cvterm->getValue('cvterm_id'),
  2616. ]);
  2617. $num_matches = $feature->find();
  2618. // Insert the feature if it does not exist otherwise perform an update.
  2619. if ($num_matches == 0) {
  2620. $feature->setValue('name', $name);
  2621. $feature->setValue('md5checksum', md5($residues));
  2622. $feature->setValue('is_analysis', $is_analysis);
  2623. $feature->setValue('is_obsolete', $is_obsolete);
  2624. try {
  2625. $feature->insert();
  2626. }
  2627. catch (Exception $e) {
  2628. $this->logMessage("Failed to insert feature '$uniquename' (" . $cvterm->getValue('name') . ").", [], TRIPAL_WARNING);
  2629. return 0;
  2630. }
  2631. }
  2632. elseif (!$add_only) {
  2633. if ($num_matches > 1) {
  2634. $this->logMessage("Failed to update feature '$uniquename' (" . $cvterm->getValue('name') . "). More than one feature exists with these criteria", [], TRIPAL_WARNING);
  2635. return 0;
  2636. }
  2637. $feature->setValue('name', $name);
  2638. $feature->setValue('md5checksum', md5($residues));
  2639. $feature->setValue('is_analysis', $is_analysis);
  2640. $feature->setValue('is_obsolete', $is_obsolete);
  2641. try {
  2642. $feature->update();
  2643. }
  2644. catch (Exception $e) {
  2645. $this->logMessage("Failed to update feature '$uniquename' (" . $cvterm->getValue('name') . ").", [], TRIPAL_WARNING);
  2646. return 0;
  2647. }
  2648. }
  2649. else {
  2650. // The feature exists and we don't want to update it so return
  2651. // a value of 0. This will stop all downstream property additions
  2652. return $feature;
  2653. }
  2654. // Add the analysisfeature entry to the analysisfeature table if
  2655. // it doesn't already exist.
  2656. $af = new ChadoRecord('analysisfeature');
  2657. $af->setValues([
  2658. 'analysis_id' => $analysis->getValue('analysis_id'),
  2659. 'feature_id' => $feature->getID(),
  2660. ]);
  2661. $num_afs = $af->find();
  2662. if ($num_afs == 0) {
  2663. // if a score is available then set that to be the significance field
  2664. if (strcmp($score, '.') != 0) {
  2665. $af->setValue('significance', $score);
  2666. }
  2667. try {
  2668. $af->insert();
  2669. }
  2670. catch (Exception $e) {
  2671. $this->logMessage("Could not add analysisfeature record: " . $analysis->getValue('analysis_id') . ", " . $feature->getID() . ". " . $e->getMessage(), [], TRIPAL_WARNING);
  2672. }
  2673. }
  2674. else {
  2675. // if a score is available then set that to be the significance field
  2676. $new_vals = [];
  2677. if (strcmp($score, '.') != 0) {
  2678. $af->setValue('significance', $score);
  2679. }
  2680. else {
  2681. $af->setValue('significance', '__NULL__');
  2682. }
  2683. if (!$add_only) {
  2684. try {
  2685. $af->update();
  2686. }
  2687. catch (Exception $e) {
  2688. $this->logMessage("Could not update analysisfeature record: $analysis_id, " . $feature->getID() . ". " . $e->getMessage(), [], TRIPAL_WARNING);
  2689. }
  2690. }
  2691. }
  2692. return $feature;
  2693. }
  2694. /**
  2695. * Insert the location of the feature
  2696. *
  2697. * @param $feature
  2698. * @param $organism
  2699. * @param $landmark
  2700. * @param $fmin
  2701. * @param $fmax
  2702. * @param $strand
  2703. * @param $phase
  2704. * @param $is_fmin_partial
  2705. * @param $is_fmax_partial
  2706. * @param $residue_info
  2707. * @param $locgroup
  2708. * @param $landmark_type_id
  2709. * @param $landmark_organism_id
  2710. * @param $create_landmark
  2711. * @param $landmark_is_target
  2712. *
  2713. * @ingroup gff3_loader
  2714. */
  2715. private function loadFeatureLoc($feature, $organism, $landmark, $fmin,
  2716. $fmax, $strand, $phase, $is_fmin_partial, $is_fmax_partial, $residue_info, $locgroup,
  2717. $landmark_type_id = '', $landmark_organism_id = '', $create_landmark = 0,
  2718. $landmark_is_target = 0) {
  2719. $srcfeature = new ChadoRecord('feature');
  2720. $srcfeature->setValues([
  2721. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  2722. 'uniquename' => $landmark,
  2723. ]);
  2724. if ($landmark_type_id) {
  2725. $srcfeature->setValue('type_id', $landmark_type_id);
  2726. }
  2727. $num_srcf = $srcfeature->find();
  2728. if ($num_srcf == 0) {
  2729. // so we couldn't find the landmark using the uniquename. Let's try the 'name'.
  2730. // if we return only a single result then we can proceed. Otherwise give an
  2731. $srcfeature = new ChadoRecord('feature');
  2732. $srcfeature->setValues([
  2733. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  2734. 'name' => $landmark,
  2735. ]);
  2736. if ($landmark_type_id) {
  2737. $srcfeature->setValue('type_id', $landmark_type_id);
  2738. }
  2739. $num_srcf = $srcfeature->find();
  2740. if ($num_srcf == 0) {
  2741. // if the landmark is the target feature in a matched alignment then try one more time to
  2742. // find it by querying any feature with the same uniquename. If we find one then use it.
  2743. if ($landmark_is_target) {
  2744. $srcfeature = new ChadoRecord('feature');
  2745. $srcfeature->setValues([
  2746. 'uniquename' => $landmark,
  2747. ]);
  2748. $num_srcf = $srcfeature->find();
  2749. if ($num_srcf > 1) {
  2750. $this->logMessage("Multiple landmarks exist for a matached target with the name: '%landmark'. Cannot " .
  2751. "resolve which one to use. Cannot add the feature location record.",
  2752. ['%landmark' => $landmark], TRIPAL_WARNING);
  2753. }
  2754. }
  2755. if ($num_srcf == 0) {
  2756. // we couldn't find the landmark feature, so if the user has requested we create it then do so
  2757. // but only if we have a type id
  2758. if ($create_landmark and $landmark_type_id) {
  2759. $srcfeature = new ChadoRecord('feature');
  2760. $srcfeature->setValues([
  2761. 'organism_id' => $landmark_organism_id ? $landmark_organism_id : $organism->organism_id,
  2762. 'name' => $landmark,
  2763. 'uniquename' => $landmark,
  2764. 'type_id' => $landmark_type_id,
  2765. ]);
  2766. try {
  2767. $srcfeature->insert();
  2768. }
  2769. catch (Exception $e) {
  2770. $this->logMessage("Cannot find landmark feature: '%landmark', nor could it be inserted. " . $e->getMessage() ,
  2771. ['%landmark' => $landmark], TRIPAL_WARNING);
  2772. return 0;
  2773. }
  2774. }
  2775. else {
  2776. $this->logMessage("Cannot find unique landmark feature: '%landmark'.",
  2777. ['%landmark' => $landmark], TRIPAL_WARNING);
  2778. return 0;
  2779. }
  2780. }
  2781. }
  2782. elseif ($num_srcf > 1) {
  2783. $this->logMessage("multiple landmarks exist with the name: '%landmark'. Cannot " .
  2784. "resolve which one to use. Cannot add the feature location record.",
  2785. ['%landmark' => $landmark], TRIPAL_WARNING);
  2786. return 0;
  2787. }
  2788. }
  2789. elseif ($num_srcf > 1) {
  2790. $this->logMessage("multiple landmarks exist with the name: '%landmark'. Cannot " .
  2791. "resolve which one to use. Cannot add the feature location record.",
  2792. ['%landmark' => $landmark, TRIPAL_WARNING]);
  2793. return 0;
  2794. }
  2795. // TODO: create an attribute that recognizes the residue_info,locgroup,
  2796. // is_fmin_partial and is_fmax_partial, right now these are
  2797. // hardcoded to be false and 0 below.
  2798. // check to see if this featureloc already exists, but also keep track of the
  2799. // last rank value
  2800. $rank = 0;
  2801. $exists = 0;
  2802. $select = ['feature_id' => $feature->getID()];
  2803. $options = [
  2804. 'order_by' => [
  2805. 'rank' => 'ASC',
  2806. ],
  2807. ];
  2808. $locrecs = chado_select_record('featureloc', ['*'], $select, $options);
  2809. foreach ($locrecs as $locrec) {
  2810. // it is possible for the featureloc->srcfeature_id to be NULL.
  2811. // This can happen if the srcfeature is not known (according to chado
  2812. // table field descriptions). If it's null then just skip this entry.
  2813. if (!$locrec->srcfeature_id) {
  2814. continue;
  2815. }
  2816. $select = ['feature_id' => $locrec->srcfeature_id];
  2817. $columns = ['feature_id', 'name'];
  2818. $locsfeature = chado_select_record('feature', $columns, $select);
  2819. // the source feature name and at least the fmin and fmax must be the same
  2820. // for an update of the featureloc, otherwise we'll insert a new record.
  2821. if (strcmp($locsfeature[0]->name, $landmark) == 0 and
  2822. ($locrec->fmin == $fmin or $locrec->fmax == $fmax)) {
  2823. $featureloc = new ChadoRecord('featureloc');
  2824. $featureloc->setValue('featureloc_id', $locrec->featureloc_id);
  2825. $values = [];
  2826. $exists = 1;
  2827. if ($featureloc->fmin != $fmin) {
  2828. $featureloc->setValue('fmin', $fmin);
  2829. }
  2830. if ($featureloc->fmax != $fmax) {
  2831. $featureloc->setValue('fmax', $fmax);
  2832. }
  2833. if ($featureloc->strand != $strand) {
  2834. $featureloc->setValue('strand', $strand);
  2835. }
  2836. if (count($featureloc->getValues()) > 0) {
  2837. $featureloc->update();
  2838. }
  2839. }
  2840. $rank = $locrec->rank + 1;
  2841. }
  2842. if (!$exists) {
  2843. // this feature location is new so add it
  2844. if (strcmp($is_fmin_partial, 'f') == 0 or !$is_fmin_partial) {
  2845. $is_fmin_partial = 'FALSE';
  2846. }
  2847. elseif (strcmp($is_fmin_partial, 't') == 0 or $is_fmin_partial == 1) {
  2848. $is_fmin_partial = 'TRUE';
  2849. }
  2850. if (strcmp($is_fmax_partial, 'f') == 0 or !$is_fmax_partial) {
  2851. $is_fmax_partial = 'FALSE';
  2852. }
  2853. elseif (strcmp($is_fmax_partial, 't') == 0 or $is_fmax_partial == 1) {
  2854. $is_fmax_partial = 'TRUE';
  2855. }
  2856. $featureloc = new ChadoRecord('featureloc');
  2857. $featureloc->setValues([
  2858. 'feature_id' => $feature->getID(),
  2859. 'srcfeature_id' => $srcfeature->getID(),
  2860. 'fmin' => $fmin,
  2861. 'is_fmin_partial' => $is_fmin_partial,
  2862. 'fmax' => $fmax,
  2863. 'is_fmax_partial' => $is_fmax_partial,
  2864. 'strand' => $strand,
  2865. 'residue_info' => $residue_info,
  2866. 'locgroup' => $locgroup,
  2867. 'rank' => $rank,
  2868. ]);
  2869. if (!$residue_info) {
  2870. $featureloc->setValue('residue_info', '__NULL__');
  2871. }
  2872. if ($phase) {
  2873. $featureloc->setValue('phase', $phase);
  2874. }
  2875. $featureloc->insert();
  2876. }
  2877. return 1;
  2878. }
  2879. /**
  2880. * Load a preoprty (featurepop) for the feature
  2881. *
  2882. * @param $feature
  2883. * @param $property
  2884. * @param $value
  2885. *
  2886. * @ingroup gff3_loader
  2887. */
  2888. private function loadProperty($feature, $property, $value) {
  2889. // First make sure the cvterm exists. if not, then add it.
  2890. $result = $this->getCvterm($property, $this->feature_property_cv_id);
  2891. // If we don't have a property like this already, then add it otherwise,
  2892. // just return.
  2893. if (empty($result)) {
  2894. $term = [
  2895. 'id' => "local:$property",
  2896. 'name' => $property,
  2897. 'is_obsolete' => 0,
  2898. 'cv_name' => 'feature_property',
  2899. 'db_name' => 'local',
  2900. 'is_relationship' => FALSE,
  2901. ];
  2902. $cvterm = (object) chado_insert_cvterm($term, ['update_existing' => FALSE]);
  2903. if (!$cvterm) {
  2904. $this->logMessage("Cannot add cvterm, $property.", [], TRIPAL_WARNING);
  2905. return 0;
  2906. }
  2907. }
  2908. else {
  2909. $cvterm = $result;
  2910. }
  2911. // Check to see if the property already exists for this feature
  2912. // if it does but the value is unique then increment the rank and add it.
  2913. // if the value is not unique then don't add it.
  2914. $add = 1;
  2915. $rank = 0;
  2916. $select = [
  2917. 'feature_id' => $feature->getId(),
  2918. 'type_id' => $cvterm->cvterm_id,
  2919. ];
  2920. $options = [
  2921. 'order_by' => [
  2922. 'rank' => 'ASC',
  2923. ],
  2924. ];
  2925. $results = chado_select_record('featureprop', ['*'], $select, $options);
  2926. foreach ($results as $prop) {
  2927. if (strcmp($prop->value, $value) == 0) {
  2928. $add = NULL; // don't add it, it already exists
  2929. }
  2930. $rank = $prop->rank + 1;
  2931. }
  2932. // add the property if we pass the check above
  2933. if ($add) {
  2934. $values = [
  2935. 'feature_id' => $feature->getID(),
  2936. 'type_id' => $cvterm->cvterm_id,
  2937. 'value' => $value,
  2938. 'rank' => $rank,
  2939. ];
  2940. $result = chado_insert_record('featureprop', $values);
  2941. if (!$result) {
  2942. $this->logMessage("cannot add featureprop, $property.", [], TRIPAL_WARNING);
  2943. }
  2944. }
  2945. }
  2946. /**
  2947. * Load the FASTA sequences at the bottom of a GFF3 file
  2948. *
  2949. * @param $fh
  2950. * @param $interval
  2951. * @param $num_read
  2952. * @param $line_num
  2953. * @param $filesize
  2954. *
  2955. * @ingroup gff3_loader
  2956. */
  2957. private function loadFasta($fh, $interval, &$num_read, &$line_num, $filesize) {
  2958. $this->logMessage("Loading FASTA sequences...");
  2959. $residues = '';
  2960. $id = NULL;
  2961. // iterate through the remaining lines of the file
  2962. while ($line = fgets($fh)) {
  2963. $line_num++;
  2964. $size = drupal_strlen($line);
  2965. $this->addItemsHandled($size);
  2966. $num_read += $size;
  2967. $line = trim($line);
  2968. // if we encounter a definition line then get the name, uniquename,
  2969. // accession and relationship subject from the definition line
  2970. if (preg_match('/^>/', $line)) {
  2971. // if we are beginning a new sequence then save to the database the last one we just finished.
  2972. if ($id) {
  2973. $values = ['uniquename' => $id];
  2974. $result = chado_select_record('tripal_gff_temp', ['*'], $values);
  2975. if (count($result) == 0) {
  2976. $this->logMessage('Cannot find feature to assign FASTA sequence: %uname.',
  2977. ['%uname' => $id], TRIPAL_WARNING);
  2978. }
  2979. else {
  2980. // if we have a feature then add the residues
  2981. $feature = $result[0];
  2982. $values = [
  2983. 'residues' => $residues,
  2984. 'seqlen' => strlen($residues),
  2985. ];
  2986. $match = ['feature_id' => $feature->feature_id];
  2987. chado_update_record('feature', $match, $values);
  2988. }
  2989. }
  2990. // get the feature ID for this ID from the tripal_gff_temp table. It
  2991. // should be the name up to the first space
  2992. $id = preg_replace('/^>([^\s]+).*$/', '\1', $line);
  2993. $residues = '';
  2994. }
  2995. else {
  2996. $residues .= trim($line);
  2997. }
  2998. }
  2999. // add in the last sequence
  3000. $values = ['uniquename' => $id];
  3001. $result = chado_select_record('tripal_gff_temp', ['*'], $values);
  3002. if (count($result) == 0) {
  3003. $this->logMessage('Cannot find feature to assign FASTA sequence: %uname.',
  3004. ['%uname' => $id], TRIPAL_WARNING);
  3005. }
  3006. else {
  3007. // if we have a feature then add the residues
  3008. $feature = $result[0];
  3009. $values = [
  3010. 'residues' => $residues,
  3011. 'seqlen' => strlen($residues),
  3012. ];
  3013. $match = ['feature_id' => $feature->feature_id];
  3014. chado_update_record('feature', $match, $values);
  3015. }
  3016. }
  3017. /**
  3018. * Load the target attribute of a gff3 record
  3019. *
  3020. * @param $feature
  3021. * @param $tags
  3022. * @param $target_organism_id
  3023. * @param $target_type
  3024. * @param $create_target
  3025. * @param $attr_locgroup
  3026. *
  3027. * @ingroup gff3_loader
  3028. */
  3029. private function loadTarget($feature, $tags, $target_organism_id, $target_type, $create_target, $attr_locgroup) {
  3030. // format is: "target_id start end [strand]", where strand is optional and may be "+" or "-"
  3031. $matched = preg_match('/^(.*?)\s+(\d+)\s+(\d+)(\s+[\+|\-])*$/', trim($tags['Target'][0]), $matches);
  3032. // the organism and type of the target may also be specified as an attribute. If so, then get that
  3033. // information
  3034. $gff_target_organism = array_key_exists('target_organism', $tags) ? $tags['target_organism'][0] : '';
  3035. $gff_target_type = array_key_exists('target_type', $tags) ? $tags['target_type'][0] : '';
  3036. // if we have matches and the Target is in the correct format then load the alignment
  3037. if ($matched) {
  3038. $target_feature = $matches[1];
  3039. $start = $matches[2];
  3040. $end = $matches[3];
  3041. // if we have an optional strand, convert it to a numeric value.
  3042. if (!empty($matches[4])) {
  3043. if (preg_match('/^\+$/', trim($matches[4]))) {
  3044. $target_strand = 1;
  3045. }
  3046. elseif (preg_match('/^\-$/', trim($matches[4]))) {
  3047. $target_strand = -1;
  3048. }
  3049. else {
  3050. $target_strand = 0;
  3051. }
  3052. }
  3053. else {
  3054. $target_strand = 0;
  3055. }
  3056. $target_fmin = $start - 1;
  3057. $target_fmax = $end;
  3058. if ($end < $start) {
  3059. $target_fmin = $end - 1;
  3060. $target_fmax = $start;
  3061. }
  3062. // default the target organism to be the value passed into the function, but if the GFF
  3063. // file species the target organism then use that instead.
  3064. $t_organism_id = $target_organism_id;
  3065. if ($gff_target_organism) {
  3066. // get the genus and species
  3067. $success = preg_match('/^(.*?):(.*?)$/', $gff_target_organism, $matches);
  3068. if ($success) {
  3069. $values = [
  3070. 'genus' => $matches[1],
  3071. 'species' => $matches[2],
  3072. ];
  3073. $torganism = chado_select_record('organism', ['organism_id'], $values);
  3074. if (count($torganism) == 1) {
  3075. $t_organism_id = $torganism[0]->organism_id;
  3076. }
  3077. else {
  3078. $this->logMessage("Cannot find organism for target %target.",
  3079. ['%target' => $gff_target_organism], TRIPAL_WARNING);
  3080. $t_organism_id = '';
  3081. }
  3082. }
  3083. else {
  3084. $this->logMessage("The target_organism attribute is improperly formatted: %target. " .
  3085. "It should be target_organism=genus:species.",
  3086. ['%target' => $gff_target_organism], TRIPAL_WARNING);
  3087. $t_organism_id = '';
  3088. }
  3089. }
  3090. // default the target type to be the value passed into the function, but if the GFF file
  3091. // species the target type then use that instead
  3092. $t_type_id = '';
  3093. if ($target_type) {
  3094. $values = [
  3095. 'name' => $target_type,
  3096. 'cv_id' => [
  3097. 'name' => 'sequence',
  3098. ],
  3099. ];
  3100. $type = chado_select_record('cvterm', ['cvterm_id'], $values);
  3101. if (count($type) == 1) {
  3102. $t_type_id = $type[0]->cvterm_id;
  3103. }
  3104. else {
  3105. throw new Exception(t("The target type does not exist in the sequence ontology: %type. ",
  3106. ['%type' => $target_type]));
  3107. }
  3108. }
  3109. if ($gff_target_type) {
  3110. $values = [
  3111. 'name' => $gff_target_type,
  3112. 'cv_id' => [
  3113. 'name' => 'sequence',
  3114. ],
  3115. ];
  3116. // get the cvterm_id for the target type
  3117. $type = chado_select_record('cvterm', ['cvterm_id'], $values);
  3118. if (count($type) == 1) {
  3119. $t_type_id = $type[0]->cvterm_id;
  3120. }
  3121. else {
  3122. // check to see if this is a synonym
  3123. $sql = "
  3124. SELECT CVTS.cvterm_id
  3125. FROM {cvtermsynonym} CVTS
  3126. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = CVTS.cvterm_id
  3127. INNER JOIN {cv} CV ON CV.cv_id = CVT.cv_id
  3128. WHERE CV.name = 'sequence' and CVTS.synonym = :synonym
  3129. ";
  3130. $synonym = chado_query($sql, [':synonym' => $gff_target_type])->fetchObject();
  3131. if ($synonym) {
  3132. $t_type_id = $synonym->cvterm_id;
  3133. }
  3134. else {
  3135. $this->logMessage("The target_type attribute does not exist in the sequence ontology: %type.",
  3136. ['%type' => $gff_target_type], TRIPAL_WARNING);
  3137. $t_type_id = '';
  3138. }
  3139. }
  3140. }
  3141. // we want to add a featureloc record that uses the target feature as the srcfeature (landmark)
  3142. // and the landmark as the feature.
  3143. $this->loadFeatureLoc($feature, NULL, $target_feature, $target_fmin,
  3144. $target_fmax, $target_strand, NULL, NULL, NULL, NULL,
  3145. $attr_locgroup, $t_type_id, $t_organism_id, $create_target, TRUE);
  3146. }
  3147. // the target attribute is not correctly formatted
  3148. else {
  3149. $this->logMessage("Could not add 'Target' alignment as it is improperly formatted: '%target'",
  3150. ['%target' => $tags['Target'][0]], TRIPAL_ERROR);
  3151. }
  3152. }
  3153. }