GFF3Importer.inc 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714
  1. <?php
  2. class GFF3Importer extends TripalImporter {
  3. /**
  4. * The name of this loader. This name will be presented to the site
  5. * user.
  6. */
  7. public static $name = 'Chado GFF3 File Loader';
  8. /**
  9. * The machine name for this loader. This name will be used to construct
  10. * the URL for the loader.
  11. */
  12. public static $machine_name = 'chado_gff3_loader';
  13. /**
  14. * A brief description for this loader. This description will be
  15. * presented to the site user.
  16. */
  17. public static $description = 'Import a GFF3 file into Chado';
  18. /**
  19. * An array containing the extensions of allowed file types.
  20. */
  21. public static $file_types = ['gff', 'gff3'];
  22. /**
  23. * Provides information to the user about the file upload. Typically this
  24. * may include a description of the file types allowed.
  25. */
  26. public static $upload_description = 'Please provide the GFF3 file.';
  27. /**
  28. * The title that should appear above the upload button.
  29. */
  30. public static $upload_title = 'GFF3 File';
  31. /**
  32. * Text that should appear on the button at the bottom of the importer
  33. * form.
  34. */
  35. public static $button_text = 'Import GFF3 file';
  36. /**
  37. * The lines from the ##sequence-region at the top of the GFF
  38. */
  39. private $seq_region_headers = [];
  40. /**
  41. * The path to the GFF3 file.
  42. */
  43. private $gff_file = NULL;
  44. /**
  45. * The file handle for the GFF3 file.
  46. */
  47. private $gff_file_h = NULL;
  48. /**
  49. * The organism ID for this GFF file.
  50. */
  51. private $organism_id = NULL;
  52. /**
  53. * The organism ChadoRecord object that corresponds to the $organism_id value.
  54. */
  55. private $organism = NULL;
  56. /**
  57. * An array of organism records for quick lookup.
  58. */
  59. private $organism_lookup = [];
  60. /**
  61. * The analysis ID for this GFF file
  62. */
  63. private $analysis_id = NULL;
  64. /**
  65. * The analysis ChadoRecord object that corresponds to the $analysis_id value.
  66. */
  67. private $analysis = NULL;
  68. /**
  69. * A flag indicating if only new items should be added (no updates)
  70. */
  71. private $add_only = NULL;
  72. /**
  73. * A flag indicting if only existing items should be updated.
  74. */
  75. private $update = TRUE;
  76. /**
  77. * If the GFF file contains a 'Target' attribute then the feature and the
  78. * target will have an alignment created, but to find the proper target
  79. * feature the target organism must also be known. If different from the
  80. * organism specified for the GFF file, then use this argument to specify
  81. * the target organism. Only use this argument if all target sequences
  82. * belong to the same species. If the targets in the GFF file belong to
  83. * multiple different species then the organism must be specified using the
  84. * 'target_organism=genus:species' attribute in the GFF file. Default is
  85. * NULL.
  86. */
  87. private $target_organism_id = NULL;
  88. /**
  89. * If the GFF file contains a 'Target' attribute then the feature and the
  90. * target will have an alignment created, but to find the proper target
  91. * feature the target organism must also be known. This can be used to
  92. * specify the target feature type to help with identification of the
  93. * target feature. Only use this argument if all target sequences types are
  94. * the same. If the targets are of different types then the type must be
  95. * specified using the 'target_type=type' attribute in the GFF file. This
  96. * must be a valid Sequence Ontology (SO) term. Default is NULL
  97. */
  98. private $target_type = NULL;
  99. /**
  100. * A flag indicating if the target feature should be created. If FALSE
  101. * then it should already exist.
  102. */
  103. private $create_target = FALSE;
  104. /**
  105. * Set this to the line in the GFF file where importing should start. This
  106. * is useful for testing and debugging GFF files that may have problems and
  107. * you want to start at a particular line to speed testing. Default = 1
  108. */
  109. private $start_line = 1;
  110. /**
  111. * During parsing of the GFF file this keeps track of the current line
  112. * number.
  113. */
  114. private $current_line = 0;
  115. /**
  116. * A Sequence Ontology term name for the landmark sequences in the GFF
  117. * file (e.g. 'chromosome'), if the GFF file contains a '##sequence-region'
  118. * line that describes the landmark sequences. Default = ''
  119. */
  120. private $landmark_type = '';
  121. /**
  122. * The ChadoRecord object for the landmark type cvterm.
  123. */
  124. private $landmark_cvterm = NULL;
  125. /**
  126. * Regular expression to pull out the mRNA name.
  127. */
  128. private $re_mrna = '';
  129. /**
  130. * Regular expression to pull out the protein name.
  131. */
  132. private $re_protein = '';
  133. /**
  134. * A flag that indicates if a protein record should be created.
  135. * @var integer
  136. */
  137. private $skip_protein = 0;
  138. /**
  139. * Sometimes lines in the GFF file are missing the required ID attribute
  140. * that specifies the unique name of the feature. If so, you may specify
  141. * the name of an existing attribute to use for the ID.
  142. */
  143. private $alt_id_attr = '';
  144. /**
  145. * The Tripal GFF loader supports the "organism" attribute. This allows
  146. * features of a different organism to be aligned to the landmark sequence
  147. * of another species. The format of the attribute is
  148. * "organism=[genus]:[species]", where [genus] is the organism's genus and
  149. * [species] is the species name. Check this box to automatically add the
  150. * organism to the database if it does not already exists. Otherwise lines
  151. * with an oraganism attribute where the organism is not present in the
  152. * database will be skipped.
  153. */
  154. private $create_organism = FALSE;
  155. /**
  156. * Holds mapping of DB names to DB ids.
  157. */
  158. private $db_lookup = [];
  159. /**
  160. * Holds a mapping of Dbxref names to ids.
  161. */
  162. private $dbxref_lookup = [];
  163. /**
  164. * Holds a mapping of Dbxref names to cvterm ids.
  165. */
  166. private $cvterm_lookup = [];
  167. /**
  168. * Holds a mapping of synonymns to ids.
  169. */
  170. private $synonym_lookup = [];
  171. /**
  172. * Maps parents to their children and contains the ranks of the children.
  173. */
  174. private $parent_lookup = [];
  175. /**
  176. * An array that stores CVterms that have been looked up so we don't have
  177. * to do the database query every time.
  178. */
  179. private $feature_cvterm_lookup = [];
  180. /**
  181. * An array that stores CVterms that have been looked up so we don't have
  182. * to do the database query every time.
  183. */
  184. private $featureprop_cvterm_lookup = [];
  185. /**
  186. * Holds the CV term for the "exact" synonym.
  187. */
  188. private $exact_syn = NULL;
  189. /**
  190. * Holds the object for the null publication record.
  191. */
  192. private $null_pub = NULL;
  193. /**
  194. * The list of features from the GFF3 file. Each element is an
  195. * associative array of the columns from the GFF3 file, with the attribute
  196. * field being an associative array of key/value pairs.
  197. */
  198. private $features = [];
  199. /**
  200. * An associatiave array containing the pointers to the FASTA sequences
  201. * in the GFF file. We don't want to load these into memory as they
  202. * may be too big!
  203. */
  204. private $residue_index = [];
  205. /**
  206. * An array that stores landmarks objects. Landmarks should be inserted
  207. * first if they don't already exist.
  208. */
  209. private $landmarks = [];
  210. /**
  211. * A controlled vocabulary ChadoRecord object. This is the CV that will be
  212. * used to for feature properties.
  213. */
  214. private $feature_prop_cv = NULL;
  215. /**
  216. * A controlled vocabulary ChadoRecord object. This is the CV that will be
  217. * used to for feature properties.
  218. */
  219. private $feature_cv = NULL;
  220. /**
  221. * @see TripalImporter::form()
  222. */
  223. public function form($form, &$form_state) {
  224. // get the list of organisms
  225. $sql = "SELECT * FROM {organism} ORDER BY genus, species";
  226. $org_rset = chado_query($sql);
  227. $organisms = [];
  228. $organisms[''] = '';
  229. while ($organism = $org_rset->fetchObject()) {
  230. $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
  231. }
  232. $form['organism_id'] = [
  233. '#title' => t('Existing Organism'),
  234. '#type' => 'select',
  235. '#description' => t("Choose an existing organism to which the entries in the GFF file will be associated."),
  236. '#required' => TRUE,
  237. '#options' => $organisms,
  238. ];
  239. $form['create_organism'] = [
  240. '#type' => 'checkbox',
  241. '#title' => t('Create organism'),
  242. '#required' => FALSE,
  243. '#description' => t('The Tripal GFF loader supports the "organism" attribute. This allows features of a
  244. different organism to be aligned to the landmark sequence. The format of the
  245. attribute is "organism=[genus]:[species]", where [genus] is the organism\'s genus and [species] is the
  246. species name. Check this box to automatically add the organism to the database if it does not already exists.
  247. Otherwise lines with an organism attribute where the organism is not present in the database will be skipped.'),
  248. ];
  249. $form['landmark_type'] = [
  250. '#title' => t('Landmark Type'),
  251. '#type' => 'textfield',
  252. '#description' => t("Optional. Use this field to specify a Sequence Ontology type
  253. for the landmark sequences in the GFF fie (e.g. 'chromosome'). This is only needed if
  254. the landmark features (first column of the GFF3 file) are not already in the database.."),
  255. ];
  256. $form['proteins'] = [
  257. '#type' => 'fieldset',
  258. '#title' => t('Proteins'),
  259. '#collapsible' => TRUE,
  260. '#collapsed' => FALSE,
  261. ];
  262. $form['proteins']['skip_protein'] = [
  263. '#type' => 'checkbox',
  264. '#title' => t('Skip automatic protein creation'),
  265. '#required' => FALSE,
  266. '#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.'),
  267. '#default_value' => 0,
  268. ];
  269. $form['proteins']['re_mrna'] = [
  270. '#type' => 'textfield',
  271. '#title' => t('Optional. Regular expression for the mRNA name'),
  272. '#required' => FALSE,
  273. '#description' => t('If automatic protein creation is enabled, then by default the loader will give each protein a name based on the name of the corresponding mRNA followed by the "-protein" suffix.
  274. If you want to customize the name of the created protein, you can enter a regular expression that will extract portions of
  275. the mRNA unique name. For example, for a
  276. mRNA with a unique name finishing by -RX (e.g. SPECIES0000001-RA),
  277. the regular expression would be, "^(.*?)-R([A-Z]+)$". Elements surrounded by parentheses are captured as backreferences and can be used for replacement.' ),
  278. ];
  279. $form['proteins']['re_protein'] = [
  280. '#type' => 'textfield',
  281. '#title' => t('Optional. Replacement string for the protein name'),
  282. '#required' => FALSE,
  283. '#description' => t('If a regular expression is used to specify a protein name you can use the backreference tokens to extract the portion of the mRNA name that you want to use for a protein.
  284. You use a dollar sign followed by a number to indicate the backreferences. For example: "$1-P$2".'),
  285. ];
  286. $form['targets'] = [
  287. '#type' => 'fieldset',
  288. '#title' => t('Targets'),
  289. '#collapsible' => TRUE,
  290. '#collapsed' => FALSE,
  291. ];
  292. $form['targets']['adesc'] = [
  293. '#markup' => t("When alignments are represented in the GFF file (e.g. such as
  294. alignments of cDNA sequences to a whole genome, or blast matches), they are
  295. represented using two feature types: 'match' (or cDNA_match, EST_match, etc.)
  296. and 'match_part'. These features may also have a 'Target' attribute to
  297. specify the sequence that is being aligned.
  298. However, the organism to which the aligned sequence belongs may not be present in the
  299. GFF file. Here you can specify the organism and feature type of the target sequences.
  300. The options here will apply to all targets unless the organism and type are explicity
  301. set in the GFF file using the 'target_organism' and 'target_type' attributes."),
  302. ];
  303. $form['targets']['target_organism_id'] = [
  304. '#title' => t('Target Organism'),
  305. '#type' => t('select'),
  306. '#description' => t("Optional. Choose the organism to which target sequences belong.
  307. Select this only if target sequences belong to a different organism than the
  308. one specified above. And only choose an organism here if all of the target sequences
  309. belong to the same species. If the targets in the GFF file belong to multiple
  310. different species then the organism must be specified using the 'target_organism=genus:species'
  311. attribute in the GFF file."),
  312. '#options' => $organisms,
  313. ];
  314. $form['targets']['target_type'] = [
  315. '#title' => t('Target Type'),
  316. '#type' => t('textfield'),
  317. '#description' => t("Optional. If the unique name for a target sequence is not unique (e.g. a protein
  318. and an mRNA have the same name) then you must specify the type for all targets in the GFF file. If
  319. the targets are of different types then the type must be specified using the 'target_type=type' attribute
  320. in the GFF file. This must be a valid Sequence Ontology (SO) term."),
  321. ];
  322. $form['targets']['create_target'] = [
  323. '#type' => 'checkbox',
  324. '#title' => t('Create Target'),
  325. '#required' => FALSE,
  326. '#description' => t("If the target feature cannot be found, create one using the organism and type specified above, or
  327. using the 'target_organism' and 'target_type' fields specified in the GFF file. Values specified in the
  328. GFF file take precedence over those specified above."),
  329. ];
  330. // Advanced Options
  331. $form['advanced'] = [
  332. '#type' => 'fieldset',
  333. '#title' => t('Additional Options'),
  334. '#collapsible' => TRUE,
  335. '#collapsed' => FALSE,
  336. ];
  337. $form['advanced']['line_number'] = [
  338. '#type' => 'textfield',
  339. '#title' => t('Start Line Number'),
  340. '#description' => t('Enter the line number in the GFF file where you would like to begin processing. The
  341. first line is line number 1. This option is useful for examining loading problems with large GFF files.'),
  342. '#size' => 10,
  343. ];
  344. $form['advanced']['alt_id_attr'] = [
  345. '#title' => t('ID Attribute'),
  346. '#type' => t('textfield'),
  347. '#description' => t("Optional. Sometimes lines in the GFF file are missing the
  348. required ID attribute that specifies the unique name of the feature, but there
  349. may be another attribute that can uniquely identify the feature. If so,
  350. you may specify the name of the attribute to use for the name."),
  351. ];
  352. return $form;
  353. }
  354. /**
  355. * @see TripalImporter::formValidate()
  356. */
  357. public function formValidate($form, &$form_state) {
  358. $organism_id = $form_state['values']['organism_id'];
  359. $target_organism_id = $form_state['values']['target_organism_id'];
  360. $target_type = trim($form_state['values']['target_type']);
  361. $create_target = $form_state['values']['create_target'];
  362. $create_organism = $form_state['values']['create_organism'];
  363. $add_only = $form_state['values']['add_only'];
  364. $update = $form_state['values']['update'];
  365. $refresh = 0; //$form_state['values']['refresh'];
  366. $remove = 0; //$form_state['values']['remove'];
  367. $line_number = trim($form_state['values']['line_number']);
  368. $landmark_type = trim($form_state['values']['landmark_type']);
  369. $alt_id_attr = trim($form_state['values']['alt_id_attr']);
  370. $re_mrna = trim($form_state['values']['re_mrna']);
  371. $re_protein = trim($form_state['values']['re_protein']);
  372. // @coder-ignore: there are no functions being called here
  373. if (($add_only AND ($update OR $refresh OR $remove)) OR
  374. ($update AND ($add_only OR $refresh OR $remove)) OR
  375. ($refresh AND ($update OR $add_only OR $remove)) OR
  376. ($remove AND ($update OR $refresh OR $add_only))) {
  377. form_set_error('add_only', t("Please select only one checkbox from the import options section"));
  378. }
  379. if ($line_number and !is_numeric($line_number) or $line_number < 0) {
  380. form_set_error('line_number', t("Please provide an integer line number greater than zero."));
  381. }
  382. if (!($re_mrna and $re_protein) and ($re_mrna or $re_protein)) {
  383. form_set_error('re_uname', t("You must provide both a regular expression for mRNA and a replacement string for protein"));
  384. }
  385. // check the regular expression to make sure it is valid
  386. set_error_handler(function () {
  387. }, E_WARNING);
  388. $result_re = preg_match("/" . $re_mrna . "/", NULL);
  389. $result = preg_replace("/" . $re_mrna . "/", $re_protein, NULL);
  390. restore_error_handler();
  391. if ($result_re === FALSE) {
  392. form_set_error('re_mrna', 'Invalid regular expression.');
  393. }
  394. else {
  395. if ($result === FALSE) {
  396. form_set_error('re_protein', 'Invalid replacement string.');
  397. }
  398. }
  399. }
  400. /**
  401. * @see TripalImporter::run()
  402. */
  403. public function run() {
  404. $arguments = $this->arguments['run_args'];
  405. $this->gff_file = $this->arguments['files'][0]['file_path'];
  406. // Set the private member variables of this class using the loader inputs.
  407. $this->organism_id = $arguments['organism_id'];
  408. $this->analysis_id = $arguments['analysis_id'];
  409. $this->add_only = $arguments['add_only'];
  410. $this->update = $arguments['update'];
  411. $this->target_organism_id = $arguments['target_organism_id'];
  412. $this->target_type = $arguments['target_type'];
  413. $this->create_target = $arguments['create_target'];
  414. $this->start_line = $arguments['line_number'];
  415. $this->landmark_type = $arguments['landmark_type'];
  416. $this->alt_id_attr = $arguments['alt_id_attr'];
  417. $this->create_organism = $arguments['create_organism'];
  418. $this->re_mrna = $arguments['re_mrna'];
  419. $this->re_protein = $arguments['re_protein'];
  420. $this->skip_protein = $arguments['skip_protein'];
  421. // Check to see if the file is located local to Drupal
  422. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $this->gff_file;
  423. if (!file_exists($dfile)) {
  424. $this->gff_file = $dfile;
  425. }
  426. // If the file is not local to Drupal check if it exists on the system.
  427. else if (!file_exists($this->gff_file)) {
  428. throw new Exception(t("Cannot find the file: !file", ['!file' => $this->gff_file]));
  429. }
  430. // Open the GFF3 file.
  431. $this->logMessage("Opening !gff_file", ['!gff_file' => $this->gff_file]);
  432. $this->gff_file_h = fopen($this->gff_file, 'r');
  433. if (!$this->gff_file_h) {
  434. throw new Exception(t("Cannot open file: !file", ['!file' => $this->gff_file]));
  435. }
  436. // Get the feature property CV object
  437. $this->feature_prop_cv = new ChadoRecord('cv');
  438. $this->feature_prop_cv->setValues(['name' => 'feature_property']);
  439. $num_found = $this->feature_prop_cv->find();
  440. if ($num_found == 0) {
  441. throw new Exception(t("Cannot find the 'feature_property' ontology'", []));
  442. }
  443. // Get the sequence CV object.
  444. $this->feature_cv = new ChadoRecord('cv');
  445. $this->feature_cv->setValues(['name' => 'sequence']);
  446. $num_found = $this->feature_cv->find();
  447. if ($num_found == 0) {
  448. throw new Exception(t("Cannot find the 'sequence' ontology'", []));
  449. }
  450. // Get the organism object.
  451. $this->organism = new ChadoRecord('organism');
  452. $this->organism->setValues(['organism_id' => $this->organism_id]);
  453. $num_found = $this->organism->find();
  454. if ($num_found == 0) {
  455. throw new Exception(t("Cannot find the specified organism for this GFF3 file."));
  456. }
  457. // Get the analysis object.
  458. $this->analysis = new ChadoRecord('analysis');
  459. $this->analysis->setValues(['analysis_id' => $this->analysis_id]);
  460. $num_found = $this->analysis->find();
  461. if ($num_found == 0) {
  462. throw new Exception(t("Cannot find the specified organism for this GFF3 file."));
  463. }
  464. // If a landmark type was provided then get that object.
  465. if ($this->landmark_type) {
  466. $this->landmark_cvterm = new ChadoRecord('cvterm');
  467. $this->landmark_cvterm->setValues([
  468. 'cv_id' => $this->feature_cv->getValue('cv_id'),
  469. 'name' => $this->landmark_type,
  470. ]);
  471. $num_found = $this->landmark_cvterm->find();
  472. if ($num_found == 0) {
  473. throw new Exception(t('Cannot find landmark feature type \'%landmark_type\'.', ['%landmark_type' => $this->landmark_type]));
  474. }
  475. }
  476. // Load the GFF3.
  477. $this->logMessage("Step 1: Preloading GFF3 file... ");
  478. $this->parseGFF3();
  479. // Prep the database for necessary records.
  480. $this->prepSynonms();
  481. $this->prepNullPub();
  482. $this->prepDBs();
  483. $this->logMessage("Step 2: Load landmarks sequences... ");
  484. $this->findLandmarks();
  485. $this->insertLandmarks();
  486. $this->logMessage("Step 3: Find existing features... ");
  487. $this->findFeatures();
  488. $this->logMessage("Step 4: Prepare for any updates ... ");
  489. $this->deleteFeatureData();
  490. $this->logMessage("Step 5: Loading !num_features features... ",
  491. ['!num_features' => count(array_keys($this->features))]);
  492. $this->insertFeatures();
  493. $this->logMessage("Step 6: Get new feature IDs... ");
  494. $this->findFeatures();
  495. $this->logMessage("Step 7: Loading locations... ");
  496. $this->insertFeatureLocs();
  497. $this->logMessage("Step 8: Loading properties... ");
  498. $this->insertFeatureProps();
  499. $this->logMessage("Step 9: Finding synonyms (aliases)... ");
  500. $this->findSynonyms();
  501. $this->logMessage("Step 10: Loading synonsyms (aliases)... ");
  502. $this->insertSynonyms();
  503. $this->logMessage("Step 11: Loading feature synonyms (aliases)... ");
  504. $this->insertFeatureSynonyms();
  505. $this->logMessage("Step 12: Finding existing cross references... ");
  506. $this->findDbxrefs();
  507. $this->logMessage("Step 13: Loading cross references... ");
  508. $this->insertDbxrefs();
  509. $this->logMessage("Step 14: Retrieving loaded cross references... ");
  510. $this->findDbxrefs();
  511. $this->logMessage("Step 15: Loading feature cross references... ");
  512. $this->insertFeatureDbxrefs();
  513. $this->logMessage("Step 16: Loading feature ontology terms... ");
  514. $this->insertFeatureCVterms();
  515. $this->logMessage("Step 17: Associate child-parent relationships... ");
  516. $this->findChildRanks();
  517. $this->insertFeatureParents();
  518. $this->logMessage("Step 18: Loading 'derives_from' relationships... ");
  519. $this->insertFeatureDerivesFrom();
  520. $this->logMessage("Step 19: Loading Targets... ");
  521. // TODO: Target (target_organism & target_type)
  522. $this->logMessage("Step 20: Adding any missing proteins... ");
  523. // TODO: protein records.
  524. // TODO: handle is_circular (it may just need to be a property).
  525. if (!empty($this->residue_index)) {
  526. $this->logMessage("Step 21: Adding sequences if available... ");
  527. $this->insertFeatureSeqs();
  528. }
  529. }
  530. /**
  531. * Load a controlled vocabulary term.
  532. *
  533. * This method first checks if the term has already been loaded in the
  534. * feature_cvterm_lookup array, which helps a lot with performance.
  535. *
  536. * @param $type
  537. * @param $cv_id
  538. *
  539. * @ingroup gff3_loader
  540. */
  541. private function getTypeID($type, $is_prop_type) {
  542. $cv = $this->feature_cv;
  543. if ($is_prop_type) {
  544. $cv = $this->feature_prop_cv;
  545. }
  546. if ($is_prop_type) {
  547. if(array_key_exists(strtolower($type), $this->featureprop_cvterm_lookup)) {
  548. return $this->featureprop_cvterm_lookup[strtolower($type)];
  549. }
  550. }
  551. elseif (array_key_exists(strtolower($type), $this->feature_cvterm_lookup)) {
  552. return $this->feature_cvterm_lookup[strtolower($type)];
  553. }
  554. $sel_cvterm_sql = "
  555. SELECT CVT.cvterm_id
  556. FROM {cvterm} CVT
  557. LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
  558. WHERE CVT.cv_id = :cv_id and
  559. (lower(CVT.name) = lower(:name) or lower(CVTS.synonym) = lower(:synonym))
  560. ";
  561. $result = chado_query($sel_cvterm_sql, [
  562. ':cv_id' => $cv->getValue('cv_id'),
  563. ':name' => $type,
  564. ':synonym' => $type,
  565. ]);
  566. $cvterm_id = $result->fetchField();
  567. // If the term couldn't be found and it's a property term then insert it.
  568. if (!$cvterm_id) {
  569. if($is_prop_type) {
  570. $term = [
  571. 'id' => "local:$type",
  572. 'name' => $type,
  573. 'is_obsolete' => 0,
  574. 'cv_name' => $cv->getValue('name'),
  575. 'db_name' => 'local',
  576. 'is_relationship' => FALSE,
  577. ];
  578. $cvterm = (object) chado_insert_cvterm($term, ['update_existing' => FALSE]);
  579. $cvterm_id = $cvterm->cvterm_id;
  580. }
  581. else {
  582. throw new Exception(t('The CVterm, "!term", cannot be found in the vocabulary: "!cv_name".',
  583. ['!term' => $type, '!cv_name' => $cv->getValue('name')]));
  584. }
  585. }
  586. if ($is_prop_type) {
  587. $this->featureprop_cvterm_lookup[strtolower($cvterm->name)] = $cvterm_id;
  588. $this->featureprop_cvterm_lookup[strtolower($type)] = $cvterm_id;
  589. }
  590. else {
  591. $this->feature_cvterm_lookup[strtolower($cvterm->name)] = $cvterm_id;
  592. $this->feature_cvterm_lookup[strtolower($type)] = $cvterm_id;
  593. }
  594. return $cvterm_id;
  595. }
  596. /**
  597. * Makes sure Chado is ready with the necessary synonym type records.
  598. */
  599. private function prepSynonms() {
  600. // make sure we have a 'synonym_type' vocabulary
  601. $select = ['name' => 'synonym_type'];
  602. $results = chado_select_record('cv', ['*'], $select);
  603. if (count($results) == 0) {
  604. // insert the 'synonym_type' vocabulary
  605. $values = [
  606. 'name' => 'synonym_type',
  607. 'definition' => 'vocabulary for synonym types',
  608. ];
  609. $success = chado_insert_record('cv', $values, array(
  610. 'skip_validation' => TRUE,
  611. ));
  612. if (!$success) {
  613. $this->logMessage("Failed to add the synonyms type vocabulary.", [], TRIPAL_WARNING);
  614. return 0;
  615. }
  616. // now that we've added the cv we need to get the record
  617. $results = chado_select_record('cv', ['*'], $select);
  618. if (count($results) > 0) {
  619. $syncv = $results[0];
  620. }
  621. }
  622. else {
  623. $syncv = $results[0];
  624. }
  625. // get the 'exact' cvterm, which is the type of synonym we're adding
  626. $select = [
  627. 'name' => 'exact',
  628. 'cv_id' => [
  629. 'name' => 'synonym_type',
  630. ],
  631. ];
  632. $result = chado_select_record('cvterm', ['*'], $select);
  633. if (count($result) == 0) {
  634. $term = [
  635. 'name' => 'exact',
  636. 'id' => "synonym_type:exact",
  637. 'definition' => '',
  638. 'is_obsolete' => 0,
  639. 'cv_name' => $syncv->name,
  640. 'is_relationship' => FALSE,
  641. ];
  642. $syntype = chado_insert_cvterm($term, ['update_existing' => TRUE]);
  643. if (!$syntype) {
  644. $this->logMessage("Cannot add synonym type: internal:$type.", [], TRIPAL_WARNING);
  645. return 0;
  646. }
  647. }
  648. else {
  649. $syntype = $result[0];
  650. }
  651. $this->exact_syn = $syntype;
  652. }
  653. /**
  654. * Makes sure there is a null publication in the database.
  655. */
  656. private function prepNullPub(){
  657. // Check to see if we have a NULL publication in the pub table. If not,
  658. // then add one.
  659. $select = ['uniquename' => 'null'];
  660. $result = chado_select_record('pub', ['*'], $select);
  661. if (count($result) == 0) {
  662. $pub_sql = "
  663. INSERT INTO {pub} (uniquename,type_id)
  664. VALUES (:uname,
  665. (SELECT cvterm_id
  666. FROM {cvterm} CVT
  667. INNER JOIN {dbxref} DBX ON DBX.dbxref_id = CVT.dbxref_id
  668. INNER JOIN {db} DB ON DB.db_id = DBX.db_id
  669. WHERE CVT.name = :type_id))
  670. ";
  671. $status = chado_query($psql);
  672. if (!$status) {
  673. $this->logMessage("Cannot prepare statement 'ins_pub_uniquename_typeid.", [], TRIPAL_WARNING);
  674. return 0;
  675. }
  676. // Insert the null pub.
  677. $result = chado_query($pub_sql, [
  678. ':uname' => 'null',
  679. ':type_id' => 'null',
  680. ])->fetchObject();
  681. if (!$result) {
  682. $this->logMessage("Cannot add null publication needed for setup of alias.", [], TRIPAL_WARNING);
  683. return 0;
  684. }
  685. $result = chado_select_record('pub', ['*'], $select);
  686. $pub = $result[0];
  687. }
  688. else {
  689. $pub = $result[0];
  690. }
  691. $this->null_pub = $pub;
  692. }
  693. /**
  694. * Makes sure Chado is ready with the necessary DB records.
  695. */
  696. private function prepDBs() {
  697. // Get the list of database records that are needed by this GFF file. If
  698. // they do not exist then add them.
  699. $sql = "
  700. SELECT db_id
  701. FROM {db}
  702. WHERE name = :dbname";
  703. foreach (array_keys($this->db_lookup) as $dbname) {
  704. // First look for the database name if it doesn't exist then create one.
  705. // first check for the fully qualified URI (e.g. DB:<dbname>. If that
  706. // can't be found then look for the name as is. If it still can't be found
  707. // the create the database
  708. $values = ['name' => "DB:$dbname"];
  709. $db = chado_select_record('db', ['db_id'], $values);
  710. if (count($db) == 0) {
  711. $values = ['name' => "$dbname"];
  712. $db = chado_select_record('db', ['db_id'], $values);
  713. }
  714. if (count($db) == 0) {
  715. $values = [
  716. 'name' => $dbname,
  717. 'description' => 'Added automatically by the Triapl GFF loader.',
  718. ];
  719. $success = chado_insert_record('db', $values, array(
  720. 'skip_validation' => TRUE,
  721. ));
  722. if ($success) {
  723. $values = ['name' => "$dbname"];
  724. $db = chado_select_record('db', ['db_id'], $values);
  725. }
  726. else {
  727. $this->logMessage("Cannot find or add the database $dbname.", [], TRIPAL_WARNING);
  728. return 0;
  729. }
  730. }
  731. $this->db_lookup[$dbname] = $db[0]->db_id;
  732. }
  733. }
  734. /**
  735. * Parses the current line of the GFF3 file for a feature.
  736. *
  737. * @return array
  738. * An associative array containing the 9 elements othe GFF3 file. The
  739. * 9th element is an associative array of the attributes.
  740. */
  741. private function parseFeature($line) {
  742. $date = getdate();
  743. // get the columns
  744. $cols = explode("\t", $line);
  745. if (sizeof($cols) != 9) {
  746. throw new Exception(t('Improper number of columns on line %line_num: %line', ['%line_num' => $this->current_line, '%line' => $line]));
  747. }
  748. $ret = [
  749. 'line' => $this->current_line,
  750. 'landmark' => $cols[0],
  751. 'source' => $cols[1],
  752. 'type' => $cols[2],
  753. 'start' => $cols[3],
  754. 'end' => $cols[4],
  755. 'score' => $cols[5],
  756. 'strand' => $cols[6],
  757. 'phase' => $cols[7],
  758. 'attrs' => [],
  759. ];
  760. // Ready the start and stop for chado. Chado expects these positions
  761. // to be zero-based, so we substract 1 from the fmin. Also, in case
  762. // they are backwards, put them in the right order.
  763. $fmin = $ret['start'] - 1;
  764. $fmax = $ret['end'];
  765. if ($ret['end'] < $ret['start']) {
  766. $fmin = $ret['end'] - 1;
  767. $fmax = $ret['start'];
  768. }
  769. $ret['start'] = $fmin;
  770. $ret['stop'] = $fmax;
  771. // Format the strand for chado
  772. if (strcmp($ret['strand'], '.') == 0) {
  773. $ret['strand'] = 0;
  774. }
  775. elseif (strcmp($ret['strand'], '+') == 0) {
  776. $ret['strand'] = 1;
  777. }
  778. elseif (strcmp($ret['strand'], '-') == 0) {
  779. $ret['strand'] = -1;
  780. }
  781. if (strcmp($ret['phase'], '.') == 0) {
  782. if (strtolower($ret['type']) == 'cds') {
  783. $ret['phase'] = '0';
  784. }
  785. else {
  786. $ret['phase'] = '';
  787. }
  788. }
  789. $tags = [];
  790. $attr_name = '';
  791. $attr_uniquename = '';
  792. $attrs = explode(";", $cols[8]);
  793. $attr_organism = [];
  794. $attr_parent = '';
  795. $attr_others = [];
  796. $attr_aliases = [];
  797. $attr_dbxref = [];
  798. $attr_derives = [];
  799. $attr_terms = [];
  800. foreach ($attrs as $attr) {
  801. $attr = rtrim($attr);
  802. $attr = ltrim($attr);
  803. if (strcmp($attr, '') == 0) {
  804. continue;
  805. }
  806. if (!preg_match('/^[^\=]+\=.+$/', $attr)) {
  807. throw new Exception(t('Attribute is not correctly formatted on line %line_num: %attr',
  808. ['%line_num' => $this->current_line, '%attr' => $attr]));
  809. }
  810. // Break apart each attribute into key/value pairs.
  811. $tag = preg_split("/=/", $attr, 2);
  812. // Multiple values of an attribute are separated by commas
  813. $tag_name = $tag[0];
  814. if (!array_key_exists($tag_name, $tags)) {
  815. $tags[$tag_name] = [];
  816. }
  817. $tags[$tag_name] = array_merge($tags[$tag_name], explode(",", $tag[1]));
  818. // Replace the URL escape codes for each tag
  819. for ($i = 0; $i < count($tags[$tag_name]); $i++) {
  820. $tags[$tag_name][$i] = urldecode($tags[$tag_name][$i]);
  821. }
  822. if (strcmp($tag_name, 'Alias') == 0) {
  823. $attr_aliases = array_merge($attr_aliases, $tags[$tag_name]);
  824. }
  825. elseif (strcmp($tag_name, 'Parent') == 0) {
  826. $attr_parent = urldecode($tag[1]);
  827. }
  828. elseif (strcmp($tag_name, 'Dbxref') == 0) {
  829. $attr_dbxref = array_merge($attr_dbxref, $tags[$tag_name]);
  830. }
  831. elseif (strcmp($tag_name, 'Derives_from') == 0) {
  832. $attr_derives = array_merge($attr_derives, $tags[$tag_name]);
  833. }
  834. elseif (strcmp($tag_name, 'Ontology_term') == 0) {
  835. $attr_terms = array_merge($attr_terms, $tags[$tag_name]);
  836. }
  837. elseif (strcmp($tag_name, 'organism') == 0) {
  838. $attr_organism = array_merge($attr_organism, $tags[$tag_name]);
  839. }
  840. // Get the list of non-reserved attributes these will get added
  841. // as properties to the featureprop table. The 'Note' and 'Gap'
  842. // attributes will go in as a property so those are not in the list
  843. // checked below.
  844. elseif (strcmp($tag_name, 'Name') !=0 and strcmp($tag_name, 'ID') !=0 and
  845. strcmp($tag_name, 'Alias') != 0 and strcmp($tag_name, 'Parent') != 0 and
  846. strcmp($tag_name, 'Target') != 0 and strcmp($tag_name, 'Derives_from') != 0 and
  847. strcmp($tag_name, 'Dbxref') != 0 and strcmp($tag_name, 'Ontology_term') != 0 and
  848. strcmp($tag_name, 'Is_circular') != 0 and strcmp($tag_name, 'target_organism') != 0 and
  849. strcmp($tag_name, 'target_type') != 0 and strcmp($tag_name, 'organism' != 0)) {
  850. foreach ($tags[$tag_name] as $value) {
  851. if (!array_key_exists($tag_name, $attr_others)) {
  852. $attr_others[$tag_name] = [];
  853. }
  854. $attr_others[$tag_name][] = $value;
  855. }
  856. }
  857. }
  858. // If neither name nor uniquename are provided then generate one.
  859. $names = $this->getFeatureName($tags, $ret['type'], $ret['landmark'], $fmin, $fmax);
  860. $attr_uniquename = $names['uniquename'];
  861. $attr_name = $names['name'];
  862. $ret['name'] = $attr_name;
  863. $ret['uniquename'] = $attr_uniquename;
  864. $ret['synonyms'] = $attr_aliases;
  865. // Add in the dbxref record.
  866. $ret['dbxrefs'] = [];
  867. foreach ($attr_dbxref as $key => $dbx) {
  868. $parts = explode(':', $dbx, 2);
  869. $ret['dbxrefs']["{$parts[0]}:{$parts[1]}"] = array(
  870. 'db' => $parts[0],
  871. 'accession' => $parts[1],
  872. );
  873. }
  874. // Add in the GFF source dbxref. This is needed for GBrowse.
  875. $ret['dbxrefs']["GFF_source:{$ret['source']}"] = array(
  876. 'db' => 'GFF_source',
  877. 'accession' => $ret['source'],
  878. );
  879. // Add in the ontology terms
  880. $ret['terms'] = [];
  881. foreach ($attr_terms as $key => $dbx) {
  882. $parts = explode(':', $dbx, 2);
  883. $ret['terms']["{$parts[0]}:{$parts[1]}"] = array(
  884. 'db' => $parts[0],
  885. 'accession' => $parts[1],
  886. );
  887. }
  888. // Add the derives from entry.
  889. $ret['derives_from'] = '';
  890. if (count($attr_derives) == 1) {
  891. $ret['derives_from'] = $attr_derives[0];
  892. }
  893. if (count($attr_derives) > 1) {
  894. throw new Exception(t('Each feature can only have one "Derives_from" attribute. The feature %uniquename has more than one: %derives',
  895. [
  896. '%uniquename' => $ret['uniquename'],
  897. '%derives' => $ret['derives_from'],
  898. ]));
  899. }
  900. // Now add all of the attributes into the return array.
  901. foreach ($tags as $key => $value) {
  902. $ret['attrs'][$key] = $value;
  903. }
  904. // Add the organism entry.
  905. $ret['organism'] = '';
  906. if (count($attr_organism) == 1) {
  907. $ret['organism'] = $attr_organism[0];
  908. }
  909. if (count($attr_organism) > 1) {
  910. throw new Exception(t('Each feature can only have one "organism" attribute. The feature %uniquename has more than one: %organism',
  911. [
  912. '%uniquename' => $ret['uniquename'],
  913. '%organism' => $ret['organism'],
  914. ]));
  915. }
  916. $ret['properties'] = $attr_others;
  917. $ret['parent'] = $attr_parent;
  918. return $ret;
  919. }
  920. /**
  921. * Indexes the FASTA section of the file for quick lookup.
  922. */
  923. private function indexFASTA() {
  924. // Iterate through the remaining lines of the file
  925. while ($line = fgets($this->gff_file_h)) {
  926. $this->current_line++;
  927. $this->addItemsHandled(drupal_strlen($line));
  928. // Get the ID and the current file pointer and store that for later.
  929. if (preg_match('/^>/', $line)) {
  930. $id = preg_replace('/^>([^\s]+).*$/', '\1', $line);
  931. $this->residue_index[trim($id)] = ftell($this->gff_file_h);
  932. }
  933. }
  934. }
  935. /**
  936. * Loads the actual residue information from the FASTA section of the file.
  937. */
  938. private function insertFeatureSeqs() {
  939. $num_residues = count(array_keys($this->residue_index));
  940. $this->setItemsHandled(0);
  941. $this->setTotalItems($num_residues);
  942. $count = 0;
  943. foreach ($this->residue_index as $uniquename => $offset) {
  944. $is_landmark = FALSE;
  945. if (!(array_key_exists($uniquename, $this->features) and
  946. $this->features[$uniquename]) and
  947. !(array_key_exists($uniquename, $this->landmarks) and
  948. $this->landmarks[$uniquename])) {
  949. $this->logMessage('Cannot find feature to assign FASTA sequence: %uname.',
  950. ['%uname' => $uniquename], TRIPAL_WARNING);
  951. $count++;
  952. continue;
  953. }
  954. if (array_key_exists($uniquename, $this->features)) {
  955. $feature = $this->features[$uniquename];
  956. }
  957. else {
  958. $feature = $this->landmarks[$uniquename];
  959. $is_landmark = TRUE;
  960. }
  961. $this->ensureFeatureIsLoaded($feature);
  962. $id = $feature['feature_id'];
  963. $residues = [];
  964. fseek($this->gff_file_h, $offset);
  965. while ($line = fgets($this->gff_file_h)) {
  966. if (preg_match('/^>/', $line)) {
  967. break;
  968. }
  969. $residues[] = trim($line);
  970. }
  971. $residues = implode('', $residues);
  972. $feature['residues'] = $residues;
  973. if (!$is_landmark) {
  974. $this->features[$uniquename] = $feature['feature_id'];;
  975. }
  976. else {
  977. $this->landmarks[$uniquename] = $feature['feature_id'];;
  978. }
  979. chado_update_record('feature', ['feature_id' => $id], [
  980. 'residues' => $residues,
  981. 'seqlen' => strlen($residues),
  982. 'md5checksum' => md5($residues),
  983. ]);
  984. $count++;
  985. $this->setItemsHandled($count);
  986. }
  987. }
  988. /**
  989. * Retrieves a ChadoRecord object for the landmark feature.
  990. *
  991. * @param $landmark_name
  992. * The name of the landmark to get
  993. *
  994. * @return
  995. * A feature ChadoRecord object or NULL if the landmark is missing and
  996. * $skip_on_missing is TRUE.
  997. */
  998. private function findLandmark($landmark_name) {
  999. // Before performing a database query check to see if
  1000. // this landmark is already in our lookup list.
  1001. if (array_key_exists($landmark_name, $this->landmarks)) {
  1002. return $this->landmarks[$landmark_name];
  1003. }
  1004. $landmark = new ChadoRecord('feature');
  1005. $landmark->setValues([
  1006. 'organism_id' => $this->organism_id,
  1007. 'uniquename' => $landmark_name,
  1008. ]);
  1009. if ($landmark_type) {
  1010. $landmark->setValue('type_id', $landmark_type->getValue('cvterm_id'));
  1011. }
  1012. $num_found = $landmark->find();
  1013. if ($num_found == 0) {
  1014. return NULL;
  1015. }
  1016. if ($num_found > 1) {
  1017. 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." .
  1018. "Cannot continue", [
  1019. '%landmark' => $landmark_name,
  1020. '%species' => $this->organism->getValues('genus') . " " . $this->organism->getValues('species'),
  1021. ]));
  1022. }
  1023. // The landmark was found, remember it
  1024. $this->landmarks[$landmark_name] = $landmark;
  1025. return $landmark;
  1026. }
  1027. /**
  1028. * Loads into the database any landmark sequences.
  1029. *
  1030. * @param $line
  1031. * The line from the GFF file that is the ##sequence-region comment.
  1032. */
  1033. private function insertHeaderLandmark($line) {
  1034. $region_matches = [];
  1035. if (preg_match('/^##sequence-region\s+(\w*?)\s+(\d+)\s+(\d+)$/i', $line, $region_matches)) {
  1036. $rid = $region_matches[1];
  1037. $landmark = $this->findLandmark($rid);
  1038. if (!$landmark) {
  1039. $rstart = $region_matches[2];
  1040. $rend = $region_matches[3];
  1041. if (!$this->landmark_type) {
  1042. 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.',
  1043. ['!landmark' => $rid]));
  1044. }
  1045. $this->insertLandmark($rid);
  1046. }
  1047. }
  1048. }
  1049. /**
  1050. * Loads a single landmark by name.
  1051. */
  1052. private function insertLandmark($name) {
  1053. $landmark = $this->insertFeature($this->organism, $this->analysis, $this->landmark_cvterm, $name,
  1054. $name, '', 'f', 'f', 1, 0);
  1055. $this->landmarks[$name] = $landmark->getValue('feature_id');
  1056. }
  1057. /**
  1058. *
  1059. */
  1060. private function parseGFF3() {
  1061. $filesize = filesize($this->gff_file);
  1062. $this->setTotalItems($filesize);
  1063. // Holds a unique list of cvterms for later lookup.
  1064. $feature_cvterms = [];
  1065. $featureprop_cvterms = [];
  1066. while ($line = fgets($this->gff_file_h)) {
  1067. $this->current_line++;
  1068. $this->addItemsHandled(drupal_strlen($line));
  1069. $line = trim($line);
  1070. if ($this->current_line < $this->start_line) {
  1071. continue;
  1072. }
  1073. // If we're in the FASTA file we're at the end of the features so return.
  1074. if (preg_match('/^##FASTA/i', $line)) {
  1075. $this->indexFASTA();
  1076. continue;
  1077. }
  1078. // if at the ##sequence-region line handle it.
  1079. $matches = [];
  1080. if (preg_match('/^##sequence-region\s+(\w*?)\s+(\d+)\s+(\d+)$/i', $line, $matches)) {
  1081. $this->seq_region_headers[$matches[1]] = $line;
  1082. continue;
  1083. }
  1084. // skip comments
  1085. if (preg_match('/^#/', $line)) {
  1086. continue;
  1087. }
  1088. // skip empty lines
  1089. if (preg_match('/^\s*$/', $line)) {
  1090. continue;
  1091. }
  1092. // Parse this feature from this line of the GFF3 file.
  1093. $gff_feature = $this->parseFeature($line);
  1094. $gff_feature['feature_id'] = NULL;
  1095. // A feature may get ignored. But let's default this to FALSE.
  1096. $gff_feature['skipped'] = FALSE;
  1097. // Lookup the organism ID if one is requested.
  1098. if ($gff_feature['organism']) {
  1099. $organism_id = $this->findOrganism($gff_feature['organism'], $line_num);
  1100. if ($organism_id) {
  1101. $gff_feature['organism'] = $organism_id;
  1102. }
  1103. elsE {
  1104. $gff_feature['skipped'] = TRUE;
  1105. }
  1106. }
  1107. // Add the landmark if it doesn't exist in the landmark list.
  1108. if (!array_key_exists($gff_feature['landmark'], $this->landmarks)) {
  1109. $this->landmarks[$gff_feature['landmark']] = FALSE;
  1110. }
  1111. // Organize DBs and DBXrefs for faster access later on.
  1112. foreach ($gff_feature['dbxrefs'] as $index => $info) {
  1113. if (!array_key_exists($info['db'], $this->db_lookup)) {
  1114. $this->db_lookup[$info['db']] = FALSE;
  1115. }
  1116. if (!array_key_exists($index, $this->dbxref_lookup)) {
  1117. $this->dbxref_lookup[$index] = $info;
  1118. }
  1119. }
  1120. // We want to make sure the Ontology_term attribute dbxrefs are
  1121. // also easily looked up... but we do not want to create them
  1122. // if they do not exist the precense of the 'cvterm' key will
  1123. // tell the loadDbxrefs() function to not create the term.
  1124. foreach ($gff_feature['terms'] as $index => $info) {
  1125. if (!array_key_exists($info['db'], $this->db_lookup)) {
  1126. $this->db_lookup[$info['db']] = FALSE;
  1127. }
  1128. if (!array_key_exists($index, $this->dbxref_lookup)) {
  1129. $this->dbxref_lookup[$index] = $info;
  1130. $this->dbxref_lookup[$index]['cvterm_id'] = NULL;
  1131. }
  1132. }
  1133. // Organize the CVterms for faster access later on.
  1134. if (!array_key_exists($gff_feature['type'], $feature_cvterms)) {
  1135. $feature_cvterms[$gff_feature['type']] = 0;
  1136. }
  1137. $feature_cvterms[$gff_feature['type']]++;
  1138. // Organize the feature property types for faster access later on.
  1139. foreach ($gff_feature['properties'] as $prop_name => $value) {
  1140. if (!array_key_exists($prop_name, $featureprop_cvterms)) {
  1141. $featureprop_cvterms[$prop_name] = NULL;
  1142. }
  1143. $featureprop_cvterms[$prop_name]++;
  1144. }
  1145. // Store the GFF feature details.
  1146. if ($gff_feature['uniquename'] != $gff_feature['landmark']) {
  1147. $this->features[$gff_feature['uniquename']] = $gff_feature;
  1148. }
  1149. }
  1150. // Iterate through the feature type terms and get a chado object for each.
  1151. foreach (array_keys($feature_cvterms) as $name) {
  1152. $this->getTypeID($name, FALSE);
  1153. }
  1154. // Iterate through the featureprop type terms and get a cvterm_id for
  1155. // each. If it doesn't exist then add a new record.
  1156. foreach (array_keys($featureprop_cvterms) as $name) {
  1157. $this->getTypeID($name, TRUE);
  1158. }
  1159. }
  1160. /**
  1161. * Imports the landmark features into Chado.
  1162. */
  1163. private function insertLandmarks() {
  1164. foreach ($this->landmarks as $uniquename => $feature_id) {
  1165. // If the landmark does not have an entry in the GFF lines, try to
  1166. // find or add it.
  1167. if ($feature_id === FALSE) {
  1168. // First see if there is a definition in the headers region.
  1169. if (array_key_exists($uniquename, $this->seq_region_headers)) {
  1170. $this->insertHeaderLandmark($this->seq_region_headers[$uniquename]);
  1171. }
  1172. // Second, if a landmark_type is provided then just add the landmark feature.
  1173. else if ($this->landmark_type) {
  1174. $this->insertLandmark($uniquename);
  1175. }
  1176. else {
  1177. throw new Exception(t('The landmark (reference) sequence, !landmark, is not in the database and not specified in the GFF3 file. Please either pre-load the landmark sequences or set a "Landmark Type" in the GFF importer.',
  1178. ['!landmark' => $uniquename]));
  1179. }
  1180. }
  1181. }
  1182. }
  1183. /**
  1184. * Imports the feature records into Chado.
  1185. */
  1186. private function insertFeatures() {
  1187. $batch_size = 1000;
  1188. $num_features = count(array_keys($this->features));
  1189. $num_batches = (int) ($num_features / $batch_size) + 1;
  1190. $this->setItemsHandled(0);
  1191. $this->setTotalItems($num_batches);
  1192. $init_sql = "
  1193. INSERT INTO {feature}
  1194. (uniquename, name, type_id, organism_id, residues, md5checksum,
  1195. seqlen, is_analysis, is_obsolete)
  1196. VALUES\n";
  1197. $i = 0;
  1198. $total = 0;
  1199. $batch_num = 1;
  1200. $sql = '';
  1201. $args = [];
  1202. foreach ($this->features as $feature) {
  1203. $total++;
  1204. // Only do an insert if this feature doesn't already exist in the databse.
  1205. if (!$feature['feature_id'] and !$feature['skipped']) {
  1206. $i++;
  1207. $residues = $this->getResidues($feature, FALSE);
  1208. $type_id = $this->feature_cvterm_lookup[strtolower($feature['type'])];
  1209. $sql .= "(:uniquename_$i, :name_$i, :type_id_$i, :organism_id_$i, :residues_$i, " .
  1210. " :md5checksum_$i, :seqlen_$i, FALSE, FALSE),\n";
  1211. $args[":uniquename_$i"] = $feature['uniquename'];
  1212. $args[":name_$i"] = $feature['name'];
  1213. $args[":type_id_$i"] = $type_id;
  1214. $args[":organism_id_$i"] = $feature['organism'] ? $feature['organism'] : $this->organism->getID();
  1215. $args[":residues_$i"] = $residues;
  1216. $args[":md5checksum_$i"] = $residues ? md5($residues) : '';
  1217. $args[":seqlen_$i"] = strlen($residues);
  1218. }
  1219. // If we've reached the size of the batch then let's do the insert.
  1220. if ($i == $batch_size or $total == $num_features) {
  1221. if (count($args) > 0) {
  1222. $sql = rtrim($sql, ",\n");
  1223. $sql = $init_sql . $sql;
  1224. chado_query($sql, $args);
  1225. }
  1226. $this->setItemsHandled($batch_num);
  1227. $batch_num++;
  1228. // Now reset all of the varables for the next batch.
  1229. $sql = '';
  1230. $i = 0;
  1231. $args = [];
  1232. }
  1233. }
  1234. }
  1235. /**
  1236. * Check if the features exist in the database.
  1237. */
  1238. private function findFeatures() {
  1239. $batch_size = 1000;
  1240. $num_features = count(array_keys($this->features));
  1241. $num_batches = (int) ($num_features / $batch_size) + 1;
  1242. $this->setItemsHandled(0);
  1243. $this->setTotalItems($num_batches);
  1244. $sql = "SELECT uniquename, type_id, organism_id, feature_id FROM {feature} WHERE uniquename in (:uniquenames)";
  1245. $i = 0;
  1246. $total = 0;
  1247. $batch_num = 1;
  1248. $names = [];
  1249. foreach ($this->features as $uniquename => $feature) {
  1250. $total++;
  1251. if (!$feature['feature_id']) {
  1252. $i++;
  1253. $names[] = $uniquename;
  1254. }
  1255. // If we've reached the size of the batch then let's do the select.
  1256. if ($i == $batch_size or $total == $num_features) {
  1257. if (count($names) > 0) {
  1258. $args = [':uniquenames' => $names];
  1259. $results = chado_query($sql, $args);
  1260. while ($f = $results->fetchObject()) {
  1261. $matched_feature = $this->features[$f->uniquename];
  1262. $matched_type_id = $this->feature_cvterm_lookup[strtolower($matched_feature['type'])];
  1263. $matched_organism_id = $matched_feature['organism'] ? $matched_feature['organism'] : $this->organism->getID();
  1264. if ($matched_type_id == $f->type_id and $matched_organism_id == $f->organism_id) {
  1265. $this->features[$f->uniquename]['feature_id'] = $f->feature_id;
  1266. }
  1267. }
  1268. }
  1269. $this->setItemsHandled($batch_num);
  1270. $batch_num++;
  1271. // Now reset all of the varables for the next batch.
  1272. $i = 0;
  1273. $names = [];
  1274. }
  1275. }
  1276. }
  1277. /**
  1278. * Deletes all anciallary data about a feature so we can re-insert it.
  1279. */
  1280. private function deleteFeatureData() {
  1281. $batch_size = 1000;
  1282. $num_features = count(array_keys($this->features));
  1283. $num_batches = (int) ($num_features / $batch_size) + 1;
  1284. $this->setItemsHandled(0);
  1285. $this->setTotalItems($num_batches);
  1286. $sql1 = "DELETE from {featureprop} WHERE feature_id IN (:feature_ids)";
  1287. $sql2 = "DELETE from {featureloc} WHERE feature_id IN (:feature_ids)";
  1288. $sql3 = "DELETE from {feature_cvterm} WHERE feature_id IN (:feature_ids)";
  1289. $sql4 = "DELETE from {feature_dbxref} WHERE feature_id IN (:feature_ids)";
  1290. $sql5 = "DELETE from {feature_synonym} WHERE feature_id IN (:feature_ids)";
  1291. $sql6 = "DELETE from {feature_relationship} WHERE subject_id IN (:feature_ids)";
  1292. $i = 0;
  1293. $total = 0;
  1294. $batch_num = 1;
  1295. $feature_ids = [];
  1296. foreach ($this->features as $feature) {
  1297. $total++;
  1298. if ($feature['feature_id'] and !$feature['skipped']) {
  1299. $i++;
  1300. $feature_ids[] = $feature['feature_id'];
  1301. }
  1302. // If we've reached the size of the batch then let's do the insert.
  1303. if ($i == $batch_size or $total == $num_features) {
  1304. if (count($feature_ids) > 0) {
  1305. $args[':feature_ids'] = $feature_ids;
  1306. chado_query($sql1, $args);
  1307. chado_query($sql2, $args);
  1308. chado_query($sql3, $args);
  1309. chado_query($sql4, $args);
  1310. chado_query($sql5, $args);
  1311. chado_query($sql6, $args);
  1312. }
  1313. $this->setItemsHandled($batch_num);
  1314. $batch_num++;
  1315. // Now reset all of the varables for the next batch.
  1316. $i = 0;
  1317. $feature_ids = [];
  1318. }
  1319. }
  1320. }
  1321. /**
  1322. *
  1323. */
  1324. private function insertFeatureProps(){
  1325. $batch_size = 100;
  1326. $num_features = count(array_keys($this->features));
  1327. $num_batches = (int) ($num_features / $batch_size) + 1;
  1328. $this->setItemsHandled(0);
  1329. $this->setTotalItems($num_batches);
  1330. $init_sql = "INSERT INTO {featureprop} (feature_id, type_id, value, rank) VALUES\n";
  1331. $i = 0;
  1332. $j = 0;
  1333. $total = 0;
  1334. $batch_num = 1;
  1335. $sql = '';
  1336. $args = [];
  1337. foreach ($this->features as $feature) {
  1338. $total++;
  1339. // If the feature is not skipped
  1340. if (!$feature['skipped']) {
  1341. $i++;
  1342. // Iterate through all of the properties of this feature.
  1343. foreach ($feature['properties'] as $prop_name => $values) {
  1344. foreach ($values as $rank => $value) {
  1345. $j++;
  1346. $type_id = $this->featureprop_cvterm_lookup[strtolower($prop_name)];
  1347. if (!$type_id) {
  1348. print $prop_name . "!!!!!!!!!!!!!!!!!!!!\n";
  1349. print_r($this->featureprop_cvterm_lookup);
  1350. print_r($feature['properties']);
  1351. exit;
  1352. }
  1353. $sql .= "(:feature_id_$j, :type_id_$j, :value_$j, :rank_$j),\n";
  1354. $args[":feature_id_$j"] = $feature['feature_id'];
  1355. $args[":type_id_$j"] = $type_id;
  1356. $args[":value_$j"] = $value;
  1357. $args[":rank_$j"] = $rank;
  1358. }
  1359. }
  1360. }
  1361. // If we've reached the size of the batch then let's do the insert.
  1362. if ($i == $batch_size or $total == $num_features) {
  1363. if (count($args) > 0) {
  1364. $sql = rtrim($sql, ",\n");
  1365. $sql = $init_sql . $sql;
  1366. chado_query($sql, $args);
  1367. }
  1368. $this->setItemsHandled($batch_num);
  1369. $batch_num++;
  1370. // Now reset all of the varables for the next batch.
  1371. $sql = '';
  1372. $i = 0;
  1373. $j = 0;
  1374. $args = [];
  1375. }
  1376. }
  1377. }
  1378. /**
  1379. *
  1380. */
  1381. private function insertFeatureParents(){
  1382. $batch_size = 100;
  1383. $num_parents = count(array_keys($this->parent_lookup));
  1384. $num_batches = (int) ($num_parents / $batch_size) + 1;
  1385. $this->setItemsHandled(0);
  1386. $this->setTotalItems($num_batches);
  1387. // Get the 'part_of' cvterm
  1388. $type_id = $this->getTypeID('part_of', FALSE);
  1389. $init_sql = "INSERT INTO {feature_relationship} (subject_id, object_id, type_id, rank) VALUES\n";
  1390. $i = 0;
  1391. $j = 0;
  1392. $total = 0;
  1393. $batch_num = 1;
  1394. $sql = '';
  1395. $args = [];
  1396. foreach ($this->parent_lookup as $parent => $children) {
  1397. $total++;
  1398. $parent_feature = $this->features[$parent];
  1399. if (!$parent_feature['skipped']) {
  1400. $i++;
  1401. $rank = 0;
  1402. foreach ($children as $feature_id) {
  1403. $j++;
  1404. $sql .= "(:subject_id_$j, :object_id_$j, :type_id_$j, :rank_$j),\n";
  1405. $args[":subject_id_$j"] = $feature_id;
  1406. $args[":object_id_$j"] = $this->features[$parent]['feature_id'];
  1407. $args[":type_id_$j"] = $type_id;
  1408. $args[":rank_$j"] = $rank;
  1409. $rank++;
  1410. }
  1411. }
  1412. // If we've reached the size of the batch then let's do the insert.
  1413. if ($i == $batch_size or $total == $num_parents) {
  1414. if (count($args) > 0) {
  1415. $sql = rtrim($sql, ",\n");
  1416. $sql = $init_sql . $sql;
  1417. chado_query($sql, $args);
  1418. }
  1419. $this->setItemsHandled($batch_num);
  1420. $batch_num++;
  1421. // Now reset all of the varables for the next batch.
  1422. $sql = '';
  1423. $i = 0;
  1424. $j = 0;
  1425. $args = [];
  1426. }
  1427. }
  1428. }
  1429. /**
  1430. *
  1431. */
  1432. private function findDbxrefs() {
  1433. $batch_size = 1000;
  1434. $num_dbxrefs = count(array_keys($this->dbxref_lookup));
  1435. $num_batches = (int) ($num_dbxrefs / $batch_size) + 1;
  1436. $this->setItemsHandled(0);
  1437. $this->setTotalItems($num_batches);
  1438. // DBXrefs may be already present so we'll do an initial round of
  1439. // looking for them and then insert those that don't exist.
  1440. $init_sql = "
  1441. SELECT DB.name, DBX.db_id, DBX.accession, DBX.dbxref_id, CVT.cvterm_id
  1442. FROM {dbxref} DBX
  1443. INNER JOIN {db} DB on DB.db_id = DBX.db_id
  1444. LEFT JOIN {cvterm} CVT on DBX.dbxref_id = CVT.dbxref_id
  1445. WHERE
  1446. ";
  1447. $i = 0;
  1448. $total = 0;
  1449. $batch_num = 1;
  1450. $sql = '';
  1451. $args = [];
  1452. foreach ($this->dbxref_lookup as $xref => $info) {
  1453. $i++;
  1454. $total++;
  1455. $sql .= "(DBX.accession = :accession_$i and DBX.db_id = :db_id_$i) OR\n";
  1456. $args[":accession_$i"] = $info['accession'];
  1457. $args[":db_id_$i"] = $this->db_lookup[$info['db']];
  1458. // If we've reached the size of the batch then let's do the select.
  1459. if ($i == $batch_size or $total == $num_dbxrefs) {
  1460. $sql = rtrim($sql, " OR\n");
  1461. $sql = $init_sql . $sql;
  1462. $results = chado_query($sql, $args);
  1463. while ($dbxref = $results->fetchObject()) {
  1464. $index = $dbxref->name . ':' . $dbxref->accession;
  1465. $this->dbxref_lookup[$index]['dbxref_id'] = $dbxref->dbxref_id;
  1466. if ($dbxref->cvterm_id) {
  1467. $this->cvterm_lookup[$index] = $dbxref->cvterm_id;
  1468. $this->dbxref_lookup[$index]['cvterm_id'] = $dbxref->cvterm_id;
  1469. }
  1470. }
  1471. $this->setItemsHandled($batch_num);
  1472. $batch_num++;
  1473. // Now reset all of the varables for the next batch.
  1474. $sql = '';
  1475. $i = 0;
  1476. $j = 0;
  1477. $args = [];
  1478. }
  1479. }
  1480. }
  1481. /**
  1482. * Calculates ranks for all of the children of each feature.
  1483. *
  1484. * This function should not be executed until after features are loaded
  1485. * into the database and we have feature_ids for all of them.
  1486. */
  1487. private function findChildRanks() {
  1488. // Iterate through parent-child relationships and set the ranks.
  1489. foreach ($this->features as $uniquename => $feature) {
  1490. if ($feature['parent']) {
  1491. // place features in order that they appear by their start coordinates.
  1492. $parent = $feature['parent'];
  1493. $start = $feature['start'];
  1494. $this->parent_lookup[$parent][$start] = $feature['feature_id'];
  1495. }
  1496. }
  1497. }
  1498. /**
  1499. *
  1500. */
  1501. private function findLandmarks() {
  1502. $batch_size = 1000;
  1503. $num_landmarks = count(array_keys($this->landmarks));
  1504. $num_batches = (int) ($num_landmarks / $batch_size) + 1;
  1505. $this->setItemsHandled(0);
  1506. $this->setTotalItems($num_batches);
  1507. $sql = "SELECT name, uniquename, feature_id FROM {feature} WHERE uniquename in (:landmarks)";
  1508. $i = 0;
  1509. $total = 0;
  1510. $batch_num = 1;
  1511. $names = [];
  1512. foreach ($this->landmarks as $landmark_name => $feature_id) {
  1513. $i++;
  1514. $total++;
  1515. // Only do an insert if this dbxref doesn't already exist in the databse.
  1516. // and this dbxref is from a Dbxref attribute not an Ontology_term attr.
  1517. if (!$feature_id) {
  1518. $names[] = $landmark_name;
  1519. }
  1520. // If we've reached the size of the batch then let's do the select.
  1521. if ($i == $batch_size or $total == $num_landmarks) {
  1522. if (count($names) > 0) {
  1523. $args = [':landmarks' => $names];
  1524. $results = chado_query($sql, $args);
  1525. while ($f = $results->fetchObject()) {
  1526. $this->landmarks[$f->uniquename] = $f->feature_id;
  1527. }
  1528. }
  1529. $this->setItemsHandled($batch_num);
  1530. $batch_num++;
  1531. // Now reset all of the varables for the next batch.
  1532. $i = 0;
  1533. $j = 0;
  1534. $names = [];
  1535. }
  1536. }
  1537. }
  1538. /**
  1539. *
  1540. */
  1541. private function insertDbxrefs() {
  1542. $batch_size = 1000;
  1543. $num_dbxrefs = count(array_keys($this->dbxref_lookup));
  1544. $num_batches = (int) ($num_dbxrefs / $batch_size) + 1;
  1545. $this->setItemsHandled(0);
  1546. $this->setTotalItems($num_batches);
  1547. $init_sql = "INSERT INTO {dbxref} (db_id, accession) VALUES\n";
  1548. $i = 0;
  1549. $total = 0;
  1550. $batch_num = 1;
  1551. $sql = '';
  1552. $args = [];
  1553. foreach ($this->dbxref_lookup as $info) {
  1554. $i++;
  1555. $total++;
  1556. // Only do an insert if this dbxref doesn't already exist in the databse.
  1557. // and this dbxref is from a Dbxref attribute not an Ontology_term attr.
  1558. if (!array_key_exists('dbxref_id', $info) and
  1559. !array_key_exists('cvterm_id', $info)) {
  1560. $sql .= "(:db_id_$i, :accession_$i),\n";
  1561. $args[":db_id_$i"] = $this->db_lookup[$info['db']];
  1562. $args[":accession_$i"] = $info['accession'];
  1563. }
  1564. // If we've reached the size of the batch then let's do the insert.
  1565. if ($i == $batch_size or $total == $num_dbxrefs) {
  1566. if (count($args) > 0) {
  1567. $sql = rtrim($sql, ",\n");
  1568. $sql = $init_sql . $sql;
  1569. chado_query($sql, $args);
  1570. }
  1571. $this->setItemsHandled($batch_num);
  1572. $batch_num++;
  1573. // Now reset all of the varables for the next batch.
  1574. $sql = '';
  1575. $i = 0;
  1576. $j = 0;
  1577. $args = [];
  1578. }
  1579. }
  1580. }
  1581. /**
  1582. *
  1583. */
  1584. private function insertFeatureDbxrefs() {
  1585. $batch_size = 100;
  1586. $num_features = count(array_keys($this->features));
  1587. $num_batches = (int) ($num_features / $batch_size) + 1;
  1588. $this->setItemsHandled(0);
  1589. $this->setTotalItems($num_batches);
  1590. // Don't need to use placeholders for this insert since we are only using integers.
  1591. $init_sql = "INSERT INTO {feature_dbxref} (feature_id, dbxref_id) VALUES \n";
  1592. $i = 0;
  1593. $j = 0;
  1594. $total = 0;
  1595. $batch_num = 1;
  1596. $sql = '';
  1597. $args = [];
  1598. foreach ($this->features as $feature) {
  1599. $total++;
  1600. // If the feature is not skipped
  1601. if (!$feature['skipped']) {
  1602. $i++;
  1603. // Iterate through all of the dbxrefs of this feature.
  1604. foreach ($feature['dbxrefs'] as $index => $info) {
  1605. $j++;
  1606. $sql .= "(:feature_id_$j, :dbxref_id_$j),\n";
  1607. $args[":feature_id_$j"] = $feature['feature_id'];
  1608. $args[":dbxref_id_$j"] = $this->dbxref_lookup[$index]['dbxref_id'];
  1609. }
  1610. }
  1611. // If we've reached the size of the batch then let's do the insert.
  1612. if ($i == $batch_size or $total == $num_features) {
  1613. if (count($args) > 0) {
  1614. $sql = rtrim($sql, ",\n");
  1615. $sql = $init_sql . $sql;
  1616. chado_query($sql, $args);
  1617. }
  1618. $this->setItemsHandled($batch_num);
  1619. $batch_num++;
  1620. // Now reset all of the varables for the next batch.
  1621. $sql = '';
  1622. $i = 0;
  1623. $j = 0;
  1624. $args = [];
  1625. }
  1626. }
  1627. }
  1628. /**
  1629. *
  1630. */
  1631. private function insertFeatureCVterms() {
  1632. $batch_size = 100;
  1633. $num_features = count(array_keys($this->features));
  1634. $num_batches = (int) ($num_features / $batch_size) + 1;
  1635. $this->setItemsHandled(0);
  1636. $this->setTotalItems($num_batches);
  1637. // Don't need to use placeholders for this insert since we are only using integers.
  1638. $init_sql = "INSERT INTO {feature_cvterm} (feature_id, cvterm_id, pub_id) VALUES \n";
  1639. $i = 0;
  1640. $j = 0;
  1641. $total = 0;
  1642. $batch_num = 1;
  1643. $sql = '';
  1644. $args = [];
  1645. foreach ($this->features as $feature) {
  1646. $total++;
  1647. // If the feature is not skipped
  1648. if (!$feature['skipped']) {
  1649. $i++;
  1650. // Iterate through all of the dbxrefs of this feature.
  1651. foreach ($feature['terms'] as $index => $info) {
  1652. $j++;
  1653. $sql .= "(:feature_id_$j, :cvterm_id_$j, :pub_id_$j),\n";
  1654. $args[":feature_id_$j"] = $feature['feature_id'];
  1655. $args[":cvterm_id_$j"] = $this->cvterm_lookup[$index];
  1656. $args[":pub_id_$j"] = $this->null_pub->pub_id;
  1657. }
  1658. }
  1659. // If we've reached the size of the batch then let's do the insert.
  1660. if ($i == $batch_size or $total == $num_features) {
  1661. if (count($args) > 0) {
  1662. $sql = rtrim($sql, ",\n");
  1663. $sql = $init_sql . $sql;
  1664. chado_query($sql, $args);
  1665. }
  1666. $this->setItemsHandled($batch_num);
  1667. $batch_num++;
  1668. // Now reset all of the varables for the next batch.
  1669. $sql = '';
  1670. $i = 0;
  1671. $j = 0;
  1672. $args = [];
  1673. }
  1674. }
  1675. }
  1676. /**
  1677. *
  1678. */
  1679. private function insertFeatureDerivesFrom() {
  1680. $batch_size = 100;
  1681. $num_features = count(array_keys($this->features));
  1682. $num_batches = (int) ($num_features / $batch_size) + 1;
  1683. $this->setItemsHandled(0);
  1684. $this->setTotalItems($num_batches);
  1685. // Get the 'derives_from' cvterm
  1686. $type_id = $this->getTypeID('derives_from', FALSE);
  1687. $init_sql = "INSERT INTO {feature_relationship} (subject_id, object_id, type_id, rank) VALUES\n";
  1688. $i = 0;
  1689. $j = 0;
  1690. $total = 0;
  1691. $batch_num = 1;
  1692. $sql = '';
  1693. $args = [];
  1694. foreach ($this->features as $feature) {
  1695. $total++;
  1696. // If the feature is not skipped
  1697. if (!$feature['skipped'] and $feature['derives_from']) {
  1698. $i++;
  1699. $object_id = $this->features[$feature['derives_from']]['feature_id'];
  1700. $sql .= "(:subject_id_$i, :object_id_$i, :type_id_$i, 0),\n";
  1701. $args[":subject_id_$i"] = $feature['feature_id'];
  1702. $args[":object_id_$i"] = $object_id;
  1703. $args[":type_id_$i"] = $type_id;
  1704. }
  1705. // If we've reached the size of the batch then let's do the insert.
  1706. if ($i == $batch_size or $total == $num_features) {
  1707. if (count($args) > 0) {
  1708. $sql = rtrim($sql, ",\n");
  1709. $sql = $init_sql . $sql;
  1710. chado_query($sql, $args);
  1711. }
  1712. $this->setItemsHandled($batch_num);
  1713. $batch_num++;
  1714. // Now reset all of the varables for the next batch.
  1715. $sql = '';
  1716. $i = 0;
  1717. $j = 0;
  1718. $args = [];
  1719. }
  1720. }
  1721. }
  1722. /**
  1723. *
  1724. */
  1725. private function insertFeatureLocs() {
  1726. $batch_size = 1000;
  1727. $num_features = count(array_keys($this->features));
  1728. $num_batches = (int) ($num_features / $batch_size) + 1;
  1729. $this->setItemsHandled(0);
  1730. $this->setTotalItems($num_batches);
  1731. $init_sql = "
  1732. INSERT INTO {featureloc}
  1733. (srcfeature_id, feature_id, fmin, fmax, strand, phase, rank)
  1734. VALUES\n";
  1735. $i = 0;
  1736. $total = 0;
  1737. $batch_num = 1;
  1738. $sql = '';
  1739. $args = [];
  1740. foreach ($this->features as $feature) {
  1741. $total++;
  1742. // If the feature is not skipped
  1743. if (!$feature['skipped']) {
  1744. $i++;
  1745. // Get the rank of this feature by iterating through all siblings of the
  1746. // parent and finding where this feature is in terms of start position.
  1747. $rank = 0;
  1748. if (array_key_exists('Parent', $feature)) {
  1749. $children = $this->parent_lookup[$feature['parent']];
  1750. foreach ($children as $sib_start => $feature_id) {
  1751. if ($sib_start == $feature['start']) {
  1752. break;
  1753. }
  1754. $rank++;
  1755. }
  1756. }
  1757. $sql .= "(:srcfeature_id_$i, :feature_id_$i, :fmin_$i, :fmax_$i," .
  1758. " :strand_$i, :phase_$i, :rank_$i),\n";
  1759. $args[":srcfeature_id_$i"] = $this->landmarks[$feature['landmark']];
  1760. $args[":feature_id_$i"] = $feature['feature_id'];
  1761. $args[":fmin_$i"] = $feature['start'];
  1762. $args[":fmax_$i"] = $feature['stop'];
  1763. $args[":strand_$i"] = $feature['strand'];
  1764. $args[":phase_$i"] = $feature['phase'] ? $feature['phase'] : NULL;
  1765. $args[":rank_$i"] = $rank;
  1766. }
  1767. // If we've reached the size of the batch then let's do the insert.
  1768. if ($i == $batch_size or $total == $num_features) {
  1769. if (count($args) > 0) {
  1770. $sql = rtrim($sql, ",\n");
  1771. $sql = $init_sql . $sql;
  1772. chado_query($sql, $args);
  1773. }
  1774. $this->setItemsHandled($batch_num);
  1775. $batch_num++;
  1776. // Now reset all of the varables for the next batch.
  1777. $sql = '';
  1778. $i = 0;
  1779. $args = [];
  1780. }
  1781. }
  1782. }
  1783. /**
  1784. * Finds an organism from an organism attribute value.
  1785. */
  1786. private function findOrganism($organism_attr, $line_num) {
  1787. if (array_key_exists($organism_attr, $this->organism_lookup)) {
  1788. return $this->organism_lookup[$organism_attr];
  1789. }
  1790. // Get the organism object.
  1791. [$genus, $species] = explode(':', $organism_attr, 2);
  1792. $organism = new ChadoRecord('organism');
  1793. $organism->setValues([
  1794. 'genus' => $genus,
  1795. 'species' => $species
  1796. ]);
  1797. $num_found = $organism->find();
  1798. if ($num_found == 1){
  1799. $this->organism_lookup[$organism_attr] = $organism->getID();
  1800. return $organism->getID();
  1801. }
  1802. if ($num_found > 1) {
  1803. throw new Exception(t('Multiple organisms were found for the "organism" attribute, %organism, on line %line_num',
  1804. ['%organism' => $organism_attr, '%line_num' => $line_num]));
  1805. }
  1806. if ($this->create_organism) {
  1807. $organism->insert();
  1808. $this->organism_lookup[$organism_attr] = $organism->getID();
  1809. $gff_feature['organism'] = $organism->getID();
  1810. return $organism->getID();
  1811. }
  1812. return NULL;
  1813. }
  1814. /**
  1815. *
  1816. */
  1817. private function findSynonyms() {
  1818. $batch_size = 1000;
  1819. $num_features = count(array_keys($this->features));
  1820. $num_batches = (int) ($num_features / $batch_size) + 1;
  1821. $this->setItemsHandled(0);
  1822. $this->setTotalItems($num_batches);
  1823. $init_sql = "SELECT synonym_id, name FROM {synonym} WHERE \n";
  1824. $i = 0;
  1825. $j = 0;
  1826. $total = 0;
  1827. $batch_num = 1;
  1828. $sql = '';
  1829. $args = [];
  1830. $batch_synonyms = [];
  1831. foreach ($this->features as $uniquename => $feature) {
  1832. $i++;
  1833. $total++;
  1834. // Get all of the synonyms for this batch.
  1835. foreach ($feature['synonyms'] as $index => $synonym) {
  1836. $batch_synonyms[] = $synonym;
  1837. }
  1838. // If we've reached the size of the batch then let's do the select
  1839. if ($i == $batch_size or $total == $num_features) {
  1840. $batch_synonyms = array_unique($batch_synonyms);
  1841. foreach ($batch_synonyms as $synonym) {
  1842. $j++;
  1843. if (!array_key_exists($synonym, $this->synonym_lookup)) {
  1844. $this->synonym_lookup[$synonym] = NULL;
  1845. }
  1846. if (!$this->synonym_lookup[$synonym]) {
  1847. $sql .= "(type_id = :type_id_$j AND name = :name_$j) OR\n";
  1848. $args[":type_id_$j"] = $this->exact_syn->cvterm_id;
  1849. $args[":name_$j"] = $synonym;
  1850. }
  1851. }
  1852. if (count($args) > 0) {
  1853. $sql = rtrim($sql, " OR\n");
  1854. $sql = $init_sql . $sql;
  1855. $results = chado_query($sql, $args);
  1856. while ($synonym = $results->fetchObject()) {
  1857. $this->synonym_lookup[$synonym->name] = $synonym->synonym_id;
  1858. }
  1859. }
  1860. $this->setItemsHandled($batch_num);
  1861. $batch_num++;
  1862. // Now reset all of the varables for the next batch.
  1863. $sql = '';
  1864. $i = 0;
  1865. $j = 0;
  1866. $args = [];
  1867. $batch_synonyms = [];
  1868. }
  1869. }
  1870. }
  1871. /**
  1872. *
  1873. */
  1874. private function insertSynonyms() {
  1875. $batch_size = 1000;
  1876. $num_synonyms = count(array_keys($this->synonym_lookup));
  1877. $num_batches = (int) ($num_synonyms / $batch_size) + 1;
  1878. $this->setItemsHandled(0);
  1879. $this->setTotalItems($num_batches);
  1880. $init_sql = "INSERT INTO {synonym} (type_id, name, synonym_sgml) VALUES\n";
  1881. $i = 0;
  1882. $total = 0;
  1883. $batch_num = 1;
  1884. $sql = '';
  1885. $args = [];
  1886. foreach ($this->synonym_lookup as $synonym => $synonym_id) {
  1887. $i++;
  1888. $total++;
  1889. // Only do an insert if this dbxref doesn't already exist in the databse.
  1890. if (!$synonym_id) {
  1891. $sql .= "(:type_id_$i,:name_$i, ''),\n";
  1892. $args[":type_id_$i"] = $this->exact_syn->cvterm_id;
  1893. $args[":name_$i"] = $synonym;
  1894. }
  1895. // If we've reached the size of the batch then let's do the insert.
  1896. if ($i == $batch_size or $total == $num_synonyms) {
  1897. if (count($args) > 0) {
  1898. $sql = rtrim($sql, ",\n");
  1899. $sql = $init_sql . $sql;
  1900. chado_query($sql, $args);
  1901. }
  1902. $this->setItemsHandled($batch_num);
  1903. $batch_num++;
  1904. // Now reset all of the varables for the next batch.
  1905. $sql = '';
  1906. $i = 0;
  1907. $args = [];
  1908. }
  1909. }
  1910. // Now we need to retrieve the synonyms IDs.
  1911. $this->findSynonyms();
  1912. }
  1913. /**
  1914. *
  1915. */
  1916. private function insertFeatureSynonyms(){
  1917. $batch_size = 1000;
  1918. $num_features = count(array_keys($this->features));
  1919. $num_batches = (int) ($num_features / $batch_size) + 1;
  1920. $this->setItemsHandled(0);
  1921. $this->setTotalItems($num_batches);
  1922. $init_sql = "INSERT INTO {feature_synonym} (synonym_id, feature_id, pub_id) VALUES \n";
  1923. $i = 0;
  1924. $j = 0;
  1925. $total = 0;
  1926. $batch_num = 1;
  1927. $args = [];
  1928. foreach ($this->features as $feature) {
  1929. $total++;
  1930. // If the feature is not skipped
  1931. if (!$feature['skipped']) {
  1932. $i++;
  1933. // Handle all of the synonyms for this feature.
  1934. foreach (array_unique($feature['synonyms']) as $synonym) {
  1935. $j++;
  1936. $sql .= "(:synonym_id_$j, :feature_id_$j, :pub_id_$j),\n";
  1937. $synonym_id = $this->synonym_lookup[$synonym];
  1938. $args[":synonym_id_$j"] = $this->synonym_lookup[$synonym];
  1939. $args[":feature_id_$j"] = $feature['feature_id'];
  1940. $args[":pub_id_$j"] = $this->null_pub->pub_id;
  1941. }
  1942. }
  1943. // If we've reached the size of the batch then let's do the insert.
  1944. if ($i == $batch_size or $total == $num_features) {
  1945. if (count($args) > 0) {
  1946. $sql = rtrim($sql, ",\n");
  1947. $sql = $init_sql . $sql;
  1948. chado_query($sql, $args);
  1949. }
  1950. $this->setItemsHandled($batch_num);
  1951. $batch_num++;
  1952. // Now reset all of the varables for the next batch.
  1953. $sql = '';
  1954. $i = 0;
  1955. $j = 0;
  1956. $args = [];
  1957. }
  1958. }
  1959. }
  1960. /**
  1961. * Retrieves the residues for a given feature.
  1962. *
  1963. */
  1964. private function getResidues($feature, $is_landmark = FALSE) {
  1965. return '';
  1966. }
  1967. /**
  1968. * Determines the name for a feature using the ID and name attributes.
  1969. *
  1970. * @param $feature_attrs
  1971. * The associative array of attributes for the feature.
  1972. *
  1973. * @param $type
  1974. * The type of feature.
  1975. *
  1976. * @return array
  1977. * An associative array with 'uniquename' and 'name' keys.
  1978. */
  1979. private function getFeatureName($attrs, $type, $landmark_name, $fmin, $fmax) {
  1980. $uniquename = '';
  1981. $name = '';
  1982. // If there is no ID or name then try to create a name and ID.
  1983. if (!array_key_exists('ID', $attrs) and !array_key_exists('name', $attrs)) {
  1984. // Check if an alternate ID field is suggested, if so, then use
  1985. // that for the name.
  1986. if (array_key_exists($this->alt_id_attr, $attrs)) {
  1987. $uniquename = $attrs[$this->alt_id_attr][0];
  1988. $name = $uniquename;
  1989. }
  1990. // If the row has a parent then generate a unqiue ID
  1991. elseif (array_key_exists('Parent', $attrs)) {
  1992. $uniquename = $attrs['Parent'][0] . "-" . $type . "-" .
  1993. $landmark_name . ":" . ($fmin + 1) . ".." . $fmax;
  1994. $name = $attrs['Parent'][0] . "-" . $type;
  1995. }
  1996. // Generate a unique name based on the type and location
  1997. // and set the name to simply be the type.
  1998. else {
  1999. $uniquename = $type . "-" . $landmark_name . ":" . ($fmin + 1) . ".." . $fmax;
  2000. $name = $type . "-" . $landmark_name;
  2001. }
  2002. }
  2003. elseif (!array_key_exists('Name', $attrs)) {
  2004. $uniquename = $attrs['ID'][0];
  2005. $name = $attrs['ID'][0];
  2006. }
  2007. elseif (!array_key_exists('ID', $attrs)) {
  2008. $uniquename = $attrs['Name'][0];
  2009. $name = $attrs['Name'][0];
  2010. }
  2011. else {
  2012. $uniquename = $attrs['ID'][0];
  2013. $name = $attrs['Name'][0];
  2014. }
  2015. // Does this uniquename already exist? This can happen for subfeatures
  2016. // (e.g. CDS features) that have multiple components but are really
  2017. // all the same thing.
  2018. if (array_key_exists($uniquename, $this->features)) {
  2019. if (array_key_exists('Parent', $attrs)) {
  2020. // Iterate through the list of similar IDs and see how many we have
  2021. // then add a numeric suffix.
  2022. $i = 2;
  2023. while (array_key_exists($uniquename . "_" . $i, $this->features)) {
  2024. $i++;
  2025. }
  2026. $uniquename = $uniquename . "_" . $i;
  2027. }
  2028. else {
  2029. throw new Exception(t("A feature with the same ID exists multiple times: !uname", ['!uname' => $uniquename]));
  2030. }
  2031. }
  2032. return [
  2033. 'name' => $name,
  2034. 'uniquename' => $uniquename,
  2035. ];
  2036. }
  2037. /**
  2038. * Load the derives from attribute for a gff3 feature
  2039. *
  2040. * @param $feature
  2041. * @param $subject
  2042. * @param $organism
  2043. *
  2044. * @ingroup gff3_loader
  2045. */
  2046. private function loadDerivesFromOld($feature, $cvterm, $object,
  2047. $organism, $fmin, $fmax) {
  2048. $type = $cvterm->name;
  2049. $derivesfrom_term = $this->getCvterm('derives_from');
  2050. // First look for the object feature in the temp table to get it's type.
  2051. $values = [
  2052. 'organism_id' => $organism->organism_id,
  2053. 'uniquename' => $object,
  2054. ];
  2055. $result = chado_select_record('tripal_gff_temp', ['type_name'], $values);
  2056. $type_id = NULL;
  2057. if (count($result) > 0) {
  2058. $type_id = $this->getCvterm($result[0]->type_name)->cvterm_id ?? NULL;
  2059. }
  2060. // If the object wasn't in the temp table then look for it in the
  2061. // feature table and get it's type.
  2062. if (!$type_id) {
  2063. $result = chado_select_record('feature', ['type_id'], $values);
  2064. if (count($result) > 1) {
  2065. $this->logMessage("Cannot find feature type for, '!subject' , in 'derives_from' relationship. Multiple matching features exist with this uniquename.",
  2066. ['!subject' => $object], TRIPAL_WARNING);
  2067. return;
  2068. }
  2069. else {
  2070. if (count($result) == 0) {
  2071. $this->logMessage("Cannot find feature type for, '!subject' , in 'derives_from' relationship.",
  2072. ['!subject' => $object], TRIPAL_WARNING);
  2073. return '';
  2074. }
  2075. else {
  2076. $type_id = $result->type_id;
  2077. }
  2078. }
  2079. }
  2080. // Get the object feature.
  2081. $match = [
  2082. 'organism_id' => $organism->organism_id,
  2083. 'uniquename' => $object,
  2084. 'type_id' => $type_id,
  2085. ];
  2086. $ofeature = chado_select_record('feature', ['feature_id'], $match);
  2087. if (count($ofeature) == 0) {
  2088. $this->logMessage("Could not add 'Derives_from' relationship " .
  2089. "for %uniquename and %subject. Subject feature, '%subject', " .
  2090. "cannot be found.", [
  2091. '%uniquename' => $feature->getValue('uniquename'),
  2092. '%subject' => $subject,
  2093. ], TRIPAL_ERROR);
  2094. return;
  2095. }
  2096. // If this feature is a protein then add it to the tripal_gffprotein_temp.
  2097. if ($type == 'protein' or $type == 'polypeptide') {
  2098. $values = [
  2099. 'feature_id' => $feature->getID(),
  2100. 'parent_id' => $ofeature[0]->feature_id,
  2101. 'fmin' => $fmin,
  2102. 'fmax' => $fmax,
  2103. ];
  2104. $result = chado_insert_record('tripal_gffprotein_temp', $values);
  2105. if (!$result) {
  2106. throw new Exception(t("Cound not save record in temporary protein table, Cannot continue.", []));
  2107. }
  2108. }
  2109. // Now check to see if the relationship already exists. If it does
  2110. // then just return.
  2111. $values = [
  2112. 'object_id' => $ofeature[0]->feature_id,
  2113. 'subject_id' => $feature->getID(),
  2114. 'type_id' => $derivesfrom_term->cvterm_id,
  2115. 'rank' => 0,
  2116. ];
  2117. $rel = chado_select_record('feature_relationship', ['*'], $values);
  2118. if (count($rel) > 0) {
  2119. return;
  2120. }
  2121. // finally insert the relationship if it doesn't exist
  2122. $ret = chado_insert_record('feature_relationship', $values, array(
  2123. 'skip_validation' => TRUE,
  2124. ));
  2125. if (!$ret) {
  2126. $this->logMessage("Could not add 'Derives_from' relationship for :uniquename and :subject.",
  2127. [
  2128. ':uniquename' => $feature->getValue('uniquename'),
  2129. ':subject' => $subject,
  2130. ], TRIPAL_WARNING);
  2131. }
  2132. }
  2133. /**
  2134. * Create the feature record & link it to it's analysis
  2135. *
  2136. * @param $organism
  2137. * @param $analysis_id
  2138. * @param $cvterm
  2139. * @param $uniquename
  2140. * @param $name
  2141. * @param $residues
  2142. * @param $is_analysis
  2143. * @param $is_obsolete
  2144. * @param $add_only
  2145. * @param $score
  2146. *
  2147. * @ingroup gff3_loader
  2148. */
  2149. private function insertFeature($organism, $analysis, $cvterm, $uniquename,
  2150. $name, $residues, $is_analysis = 'f', $is_obsolete = 'f', $add_only, $score) {
  2151. if (strcmp($is_obsolete, 'f') == 0 or $is_obsolete == 0) {
  2152. $is_obsolete = 'FALSE';
  2153. }
  2154. if (strcmp($is_obsolete, 't') == 0 or $is_obsolete == 1) {
  2155. $is_obsolete = 'TRUE';
  2156. }
  2157. if (strcmp($is_analysis, 'f') == 0 or $is_analysis == 0) {
  2158. $is_analysis = 'FALSE';
  2159. }
  2160. if (strcmp($is_analysis, 't') == 0 or $is_analysis == 1) {
  2161. $is_analysis = 'TRUE';
  2162. }
  2163. // Check to see if the feature already exists.
  2164. $feature = new ChadoRecord('feature');
  2165. $feature->setValues([
  2166. 'organism_id' => $organism->getValue('organism_id'),
  2167. 'uniquename' => $uniquename,
  2168. 'type_id' => $cvterm->getValue('cvterm_id'),
  2169. ]);
  2170. $num_matches = $feature->find();
  2171. // Insert the feature if it does not exist otherwise perform an update.
  2172. if ($num_matches == 0) {
  2173. $feature->setValue('name', $name);
  2174. $feature->setValue('md5checksum', md5($residues));
  2175. $feature->setValue('is_analysis', $is_analysis);
  2176. $feature->setValue('is_obsolete', $is_obsolete);
  2177. try {
  2178. $feature->insert();
  2179. }
  2180. catch (Exception $e) {
  2181. $this->logMessage("Failed to insert feature '$uniquename' (" . $cvterm->getValue('name') . ").", [], TRIPAL_WARNING);
  2182. return 0;
  2183. }
  2184. }
  2185. elseif (!$add_only) {
  2186. if ($num_matches > 1) {
  2187. $this->logMessage("Failed to update feature '$uniquename' (" . $cvterm->getValue('name') . "). More than one feature exists with these criteria", [], TRIPAL_WARNING);
  2188. return 0;
  2189. }
  2190. $feature->setValue('name', $name);
  2191. $feature->setValue('md5checksum', md5($residues));
  2192. $feature->setValue('is_analysis', $is_analysis);
  2193. $feature->setValue('is_obsolete', $is_obsolete);
  2194. try {
  2195. $feature->update();
  2196. }
  2197. catch (Exception $e) {
  2198. $this->logMessage("Failed to update feature '$uniquename' (" . $cvterm->getValue('name') . ").", [], TRIPAL_WARNING);
  2199. return 0;
  2200. }
  2201. }
  2202. else {
  2203. // The feature exists and we don't want to update it so return
  2204. // a value of 0. This will stop all downstream property additions
  2205. return $feature;
  2206. }
  2207. // Add the analysisfeature entry to the analysisfeature table if
  2208. // it doesn't already exist.
  2209. $af = new ChadoRecord('analysisfeature');
  2210. $af->setValues([
  2211. 'analysis_id' => $analysis->getValue('analysis_id'),
  2212. 'feature_id' => $feature->getID(),
  2213. ]);
  2214. $num_afs = $af->find();
  2215. if ($num_afs == 0) {
  2216. // if a score is available then set that to be the significance field
  2217. if (strcmp($score, '.') != 0) {
  2218. $af->setValue('significance', $score);
  2219. }
  2220. try {
  2221. $af->insert();
  2222. }
  2223. catch (Exception $e) {
  2224. $this->logMessage("Could not add analysisfeature record: " . $analysis->getValue('analysis_id') . ", " . $feature->getID() . ". " . $e->getMessage(), [], TRIPAL_WARNING);
  2225. }
  2226. }
  2227. else {
  2228. // if a score is available then set that to be the significance field
  2229. $new_vals = [];
  2230. if (strcmp($score, '.') != 0) {
  2231. $af->setValue('significance', $score);
  2232. }
  2233. else {
  2234. $af->setValue('significance', '__NULL__');
  2235. }
  2236. if (!$add_only) {
  2237. try {
  2238. $af->update();
  2239. }
  2240. catch (Exception $e) {
  2241. $this->logMessage("Could not update analysisfeature record: $analysis_id, " . $feature->getID() . ". " . $e->getMessage(), [], TRIPAL_WARNING);
  2242. }
  2243. }
  2244. }
  2245. return $feature;
  2246. }
  2247. /**
  2248. * Load the target attribute of a gff3 record
  2249. *
  2250. * @param $feature
  2251. * @param $tags
  2252. * @param $target_organism_id
  2253. * @param $target_type
  2254. * @param $create_target
  2255. * @param $attr_locgroup
  2256. *
  2257. * @ingroup gff3_loader
  2258. */
  2259. private function loadTarget($feature, $tags, $target_organism_id, $target_type, $create_target, $attr_locgroup) {
  2260. // format is: "target_id start end [strand]", where strand is optional and may be "+" or "-"
  2261. $matched = preg_match('/^(.*?)\s+(\d+)\s+(\d+)(\s+[\+|\-])*$/', trim($tags['Target'][0]), $matches);
  2262. // the organism and type of the target may also be specified as an attribute. If so, then get that
  2263. // information
  2264. $gff_target_organism = array_key_exists('target_organism', $tags) ? $tags['target_organism'][0] : '';
  2265. $gff_target_type = array_key_exists('target_type', $tags) ? $tags['target_type'][0] : '';
  2266. // if we have matches and the Target is in the correct format then load the alignment
  2267. if ($matched) {
  2268. $target_feature = $matches[1];
  2269. $start = $matches[2];
  2270. $end = $matches[3];
  2271. // if we have an optional strand, convert it to a numeric value.
  2272. if (!empty($matches[4])) {
  2273. if (preg_match('/^\+$/', trim($matches[4]))) {
  2274. $target_strand = 1;
  2275. }
  2276. elseif (preg_match('/^\-$/', trim($matches[4]))) {
  2277. $target_strand = -1;
  2278. }
  2279. else {
  2280. $target_strand = 0;
  2281. }
  2282. }
  2283. else {
  2284. $target_strand = 0;
  2285. }
  2286. $target_fmin = $start - 1;
  2287. $target_fmax = $end;
  2288. if ($end < $start) {
  2289. $target_fmin = $end - 1;
  2290. $target_fmax = $start;
  2291. }
  2292. // default the target organism to be the value passed into the function, but if the GFF
  2293. // file species the target organism then use that instead.
  2294. $t_organism_id = $target_organism_id;
  2295. if ($gff_target_organism) {
  2296. // get the genus and species
  2297. $success = preg_match('/^(.*?):(.*?)$/', $gff_target_organism, $matches);
  2298. if ($success) {
  2299. $values = [
  2300. 'genus' => $matches[1],
  2301. 'species' => $matches[2],
  2302. ];
  2303. $torganism = chado_select_record('organism', ['organism_id'], $values);
  2304. if (count($torganism) == 1) {
  2305. $t_organism_id = $torganism[0]->organism_id;
  2306. }
  2307. else {
  2308. $this->logMessage("Cannot find organism for target %target.",
  2309. ['%target' => $gff_target_organism], TRIPAL_WARNING);
  2310. $t_organism_id = '';
  2311. }
  2312. }
  2313. else {
  2314. $this->logMessage("The target_organism attribute is improperly formatted: %target. " .
  2315. "It should be target_organism=genus:species.",
  2316. ['%target' => $gff_target_organism], TRIPAL_WARNING);
  2317. $t_organism_id = '';
  2318. }
  2319. }
  2320. // default the target type to be the value passed into the function, but if the GFF file
  2321. // species the target type then use that instead
  2322. $t_type_id = '';
  2323. if ($target_type) {
  2324. $values = [
  2325. 'name' => $target_type,
  2326. 'cv_id' => [
  2327. 'name' => 'sequence',
  2328. ],
  2329. ];
  2330. $type = chado_select_record('cvterm', ['cvterm_id'], $values);
  2331. if (count($type) == 1) {
  2332. $t_type_id = $type[0]->cvterm_id;
  2333. }
  2334. else {
  2335. throw new Exception(t("The target type does not exist in the sequence ontology: %type. ",
  2336. ['%type' => $target_type]));
  2337. }
  2338. }
  2339. if ($gff_target_type) {
  2340. $values = [
  2341. 'name' => $gff_target_type,
  2342. 'cv_id' => [
  2343. 'name' => 'sequence',
  2344. ],
  2345. ];
  2346. // get the cvterm_id for the target type
  2347. $type = chado_select_record('cvterm', ['cvterm_id'], $values);
  2348. if (count($type) == 1) {
  2349. $t_type_id = $type[0]->cvterm_id;
  2350. }
  2351. else {
  2352. // check to see if this is a synonym
  2353. $sql = "
  2354. SELECT CVTS.cvterm_id
  2355. FROM {cvtermsynonym} CVTS
  2356. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = CVTS.cvterm_id
  2357. INNER JOIN {cv} CV ON CV.cv_id = CVT.cv_id
  2358. WHERE CV.name = 'sequence' and CVTS.synonym = :synonym
  2359. ";
  2360. $synonym = chado_query($sql, [':synonym' => $gff_target_type])->fetchObject();
  2361. if ($synonym) {
  2362. $t_type_id = $synonym->cvterm_id;
  2363. }
  2364. else {
  2365. $this->logMessage("The target_type attribute does not exist in the sequence ontology: %type.",
  2366. ['%type' => $gff_target_type], TRIPAL_WARNING);
  2367. $t_type_id = '';
  2368. }
  2369. }
  2370. }
  2371. // we want to add a featureloc record that uses the target feature as the srcfeature (landmark)
  2372. // and the landmark as the feature.
  2373. $this->loadFeatureLoc($feature, NULL, $target_feature, $target_fmin,
  2374. $target_fmax, $target_strand, NULL, NULL, NULL, NULL,
  2375. $attr_locgroup, $t_type_id, $t_organism_id, $create_target, TRUE);
  2376. }
  2377. // the target attribute is not correctly formatted
  2378. else {
  2379. $this->logMessage("Could not add 'Target' alignment as it is improperly formatted: '%target'",
  2380. ['%target' => $tags['Target'][0]], TRIPAL_ERROR);
  2381. }
  2382. }
  2383. }