GFF3Importer.inc 94 KB

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