GFF3Importer.inc 110 KB

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