-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.py
2370 lines (1844 loc) · 92.3 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
__author__ = 'Dimitris Xenakis'
import kivy
kivy.require('1.9.0')
import threading
import time
from datetime import datetime
import urllib2
import json
import operator
import gc
import os
from functools import partial
import math
from kivy.config import Config
Config.set("kivy", "exit_on_escape", False)
Config.set("graphics", "height", 660)
Config.set("graphics", "width", 1340)
Config.set('graphics', 'show_cursor', 1)
from kivy.app import App
from kivy.core.window import Window
from kivy.factory import Factory
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.stacklayout import StackLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.scatter import Scatter
from kivy.graphics.svg import Svg
from kivy.animation import Animation
from kivy.uix.stencilview import StencilView
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.properties import BooleanProperty, StringProperty, DictProperty, ObjectProperty,\
ListProperty, NumericProperty
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.popup import Popup
from kivy.clock import Clock, mainthread
from kivy.uix.dropdown import DropDown
# Set WorldBank API static parameters.
start_url = "http://api.worldbank.org/"
end_url = "?per_page=30000&format=json"
# Set url catalogs.
countries = "countries/"
topics = "topics/"
indicators = "indicators/"
# Set url for World Development Indicators (WDI)
wdi_url = "http://api.worldbank.org/source/2/indicators/?per_page=30000&format=json"
class LabelTip(Label):
def __init__(self, **kwargs):
# make sure we aren't overriding any important functionality
super(LabelTip, self).__init__(**kwargs)
with open("./DB/tips.txt", "r") as stream:
self.text = stream.read()
class TopicToggleButton(ToggleButton):
note = StringProperty("")
class IndexToggleButton(ToggleButton):
code = StringProperty("")
note = StringProperty("")
topic = StringProperty("")
class BtnRmv(Button):
index = StringProperty("")
class SelectAll(Button):
region = ObjectProperty()
normal = StringProperty("")
class MyIndicesBar(BoxLayout):
# Link to ScreenManager
mib_my_indicators_search_sm = ObjectProperty()
def on_touch_down(self, *args):
super(MyIndicesBar, self).on_touch_down(*args)
# Check if mouse is over my_indicators_bar.
if self.collide_point(args[0].pos[0], args[0].pos[1]):
# Switch Screens.
self.mib_my_indicators_search_sm.current = "my_indicators"
class SearchBar(BoxLayout):
# Link to ScreenManager
sb_my_indicators_search_sm = ObjectProperty()
def on_touch_down(self, *args):
super(SearchBar, self).on_touch_down(*args)
# Check if mouse is over search_bar.
if self.collide_point(args[0].pos[0], args[0].pos[1]):
# This touch should not be used to defocus.
FocusBehavior.ignored_touch.append(args[0])
# Switch Screens.
self.sb_my_indicators_search_sm.current = "search_index"
class SearchArea(TextInput):
pass
class IndexStackLayout(StackLayout):
def do_layout(self, *largs):
super(IndexStackLayout, self).do_layout()
col = int((self.width-8)//380)
# Try to fix each Index button.
if col > 0:
# Calculate how many cols are inside the slider.
for button in range(1, len(IndexSelection.shown_ind_btns)+1, col):
# Prepare the list to store each button height per line.
height_list = []
# Locate the highest texture_size per line.
for step in range(col):
height_list.append(IndexSelection.shown_ind_btns[button+step].texture_size[1])
# If current is last button, break.
if button+step == len(IndexSelection.shown_ind_btns):
break
# Renew the height of each button per line, to the highest one.
for step in range(col):
IndexSelection.shown_ind_btns[button+step].height = max(height_list)+20
# If current is last button, break.
if button+step == len(IndexSelection.shown_ind_btns):
break
class CIMScreenManager(ScreenManager):
mouse_pos = ListProperty()
def __init__(self, **kwargs):
# make sure we aren't overriding any important functionality
super(CIMScreenManager, self).__init__(**kwargs)
Window.bind(mouse_pos=self.setter('mouse_pos'))
def on_mouse_pos(self, *args):
self.current_screen.mouse_pos = self.mouse_pos
class MouseScreen(Screen):
mouse_pos = ListProperty()
class IndexSelection(MouseScreen):
# Link to Update button from MainWindow.
is_update_db = ObjectProperty()
# Link to CIMScreenManager.
is_manager = ObjectProperty()
# Link to IndexCreation.
is_index_creation = ObjectProperty()
selected_indices = DictProperty({"feat_index": None, "my_indicators": {}})
coredb_py = ObjectProperty()
def __init__(self, **kwargs):
# make sure we aren't overriding any important functionality
super(IndexSelection, self).__init__(**kwargs)
self.must_build_topics = True
self.shown_ind_btns = {}
self.search_dic = None
self.topics_dic = None
# This function updates status Icon that belongs to IndexCreation Class.
@mainthread
def dl_status_icon_setter(self):
# If there is no active Indicator data download..
if not self.is_index_creation.btn_get_indicators.disabled:
# Compare my_indicators to sorted_indicators so we know if we must re-download data.
my_in = self.selected_indices["my_indicators"].keys()
my_in.sort()
# If lists are the same..
if my_in == self.is_index_creation.sorted_indicators:
self.is_index_creation.downloading_state_icon.source = './Sources/status_valid.png'
else:
self.is_index_creation.downloading_state_icon.source = './Sources/status_error.png'
# Recursively convert Unicode objects to strings objects.
def string_it(self, obj):
if isinstance(obj, dict):
return {self.string_it(key): self.string_it(value) for key, value in obj.iteritems()}
elif isinstance(obj, list):
return [self.string_it(element) for element in obj]
elif isinstance(obj, unicode):
return obj.encode('utf-8')
else:
return obj
# Function that will run every time mouse is moved.
def on_mouse_pos(self, *args):
for button in self.topics_dic.keys():
if button.collide_point(*button.to_widget(*args[1])):
button.background_normal = './Sources/button_hovered.png'
else:
button.background_normal = './Sources/button_normal.png'
# Check if mouse is over add_index_icon.
if self.add_index_icon.collide_point(*args[1]):
self.add_index_label.color = (0.34, 0.65, 0.90, 1)
else:
self.add_index_label.color = (1, 1, 1, 1)
# Check if mouse is over toggle_index_desc_icon.
if self.toggle_index_desc_icon.collide_point(*args[1]):
self.toggle_index_desc_label.color = (0.34, 0.65, 0.90, 1)
else:
self.toggle_index_desc_label.color = (1, 1, 1, 1)
# Function that clears the slider's stacklayout.
def clear_indices_stack(self):
# Clear all widgets from stack layout.
self.indices_slider_stack.clear_widgets()
# Reset slider position back to top.
self.indices_slider.scroll_y = 1
# Clear the "feat_index".
self.selected_indices["feat_index"] = None
# This function is called when an Index is selected.
def on_index_selection(self, *args):
# If current index selection is the feat_index.
if args[0] == self.selected_indices["feat_index"]:
# It means the same button has been toggled and should clear the "feat_index".
self.selected_indices["feat_index"] = None
else:
if self.selected_indices["feat_index"] is not None:
self.selected_indices["feat_index"].state = "normal"
self.selected_indices["feat_index"] = args[0]
# Reset slider position back to top.
self.index_desc_slider.scroll_y = 1
# This function is called when an Index is added to my_indicators.
def on_my_indicators(self):
# If user has selected an Index..
if not self.selected_indices["feat_index"] is None and \
not (self.selected_indices["feat_index"].text in self.selected_indices[
"my_indicators"]):
# Add Index to my_indicators.
self.selected_indices["my_indicators"][self.selected_indices["feat_index"].text] = \
self.selected_indices["feat_index"].code
# Set proper btn backgrounds based on my_indicators.
self.btn_index_background()
# Create my_index_box to hold my_index components.
my_index_box = Factory.MyIndexBox()
# Create btn_rmv_anchor to hold btn_rmv.
btn_rmv_anchor = AnchorLayout(size_hint_y=None,
height=25,
anchor_x="right",
padding=[0, 0, 10, 0])
# Create a removing index btn.
btn_rmv = Factory.BtnRmv(index=self.selected_indices["feat_index"].text,
on_release=self.rmv_my_indicators)
# Add btn_rmv in btn_rmv_anchor.
btn_rmv_anchor.add_widget(btn_rmv)
# Create my_index Label.
my_index = Factory.MyIndex(text=self.selected_indices["feat_index"].text)
# Create my_topic Label.
my_topic = Factory.MyTopic(text=self.selected_indices["feat_index"].topic)
# Add all components in my_index_box.
my_index_box.add_widget(btn_rmv_anchor)
my_index_box.add_widget(Factory.ShadeLine())
my_index_box.add_widget(my_index)
my_index_box.add_widget(my_topic)
# Bind children heights to parent box.
my_index.bind(height=self.fix_my_index_h)
my_topic.bind(height=self.fix_my_index_h)
# Add my_index_box in my_indicators_container.
self.my_indicators_container.add_widget(my_index_box)
# Switch to my_indicators.
self.my_indicators_search_sm.current = "my_indicators"
# Remove previous text inputs.
self.search_area.text = ""
# Check if indicator data must be downloaded again.
self.dl_status_icon_setter()
def rmv_my_indicators(self, *args):
# Remove index from the dict with my indices.
self.selected_indices["my_indicators"].pop(args[0].index, None)
# Remove that specific my_index_box.
self.my_indicators_container.remove_widget(args[0].parent.parent)
# Set proper btn backgrounds based on my_indicators.
self.btn_index_background()
# Check if indicator data must be downloaded again.
self.dl_status_icon_setter()
# Function that clears all search results.
def clear_search_results(self, *args):
# Clear all widgets from search_results_container.
self.search_results_container.clear_widgets()
# Reset slider position back to top.
self.search_results_slider.scroll_y = 1
# Clear search area too because user pressed the clear button.
if len(args) == 1:
# Remove previous text inputs.
self.search_area.text = ""
@staticmethod
def fix_my_index_h(*args):
# Init box height is the sum of the Top and Bottom box paddings
args[0].parent.height = args[0].parent.padding[1] + args[0].parent.padding[3]
# For each child in box add it's height to the box.
for child in args[0].parent.children:
args[0].parent.height += child.height
# This function sets proper background_normal of index buttons.
def btn_index_background(self):
# For each index button..
for btn in IndexSelection.shown_ind_btns.values():
# search if it is in my_indicators.
if btn.text in self.selected_indices["my_indicators"].keys():
btn.background_normal = './Sources/grey_btn_down.png'
btn.bold = True
else:
btn.background_normal = './Sources/wht_btn_normal.png'
btn.bold = False
def search_results(self, keyword):
# Clears all search results.
self.clear_search_results()
# Create sr_toolbox to hold sr_title and clear_sr.
sr_toolbox = BoxLayout(orientation="vertical", size_hint_y=None, height=55)
# Create search Title Label.
sr_title = Factory.SR_Title()
# Create button to clear results.
clear_sr = Factory.SR_Clear(on_press=self.clear_search_results)
# Add search Title and clear button to sr_toolbox
sr_toolbox.add_widget(clear_sr)
sr_toolbox.add_widget(sr_title)
# Add sr_toolbox to search_results_container.
self.search_results_container.add_widget(sr_toolbox)
for topic in self.search_dic:
for index in self.search_dic[topic]:
if keyword.lower() in index.lower():
# Create searched_index_box to hold searched_index components.
searched_index_box = Factory.SearchBox()
# List to store occurrences.
occurrences = []
located = None
# Convert each index into a marked index.
while located != -1:
located = index.lower().find(keyword.lower())
if located != -1:
occurrences.append(
index.partition(index[located:located+len(keyword)])[0])
occurrences.append("[color=ff0078][b]")
occurrences.append(
index.partition(index[located:located+len(keyword)])[1])
occurrences.append("[/b][/color]")
index = index.partition(index[located:located+len(keyword)])[2]
else:
occurrences.append(index)
marked_index = ''.join(occurrences)
# Create search result index Label.
my_index = Factory.SR_Index(text=marked_index)
# Create search result topic Label.
my_topic = Factory.SR_Topic(text=topic)
# Add all components in searched_index_box.
searched_index_box.add_widget(my_topic)
searched_index_box.add_widget(my_index)
# Bind children heights to parent box.
my_index.bind(height=self.fix_my_index_h)
my_topic.bind(height=self.fix_my_index_h)
# Add searched_index_box in search_results_container.
self.search_results_container.add_widget(searched_index_box)
# Show number of search results.
if len(self.search_results_container.children) > 1:
sr_title.text = str(len(self.search_results_container.children)-1) + " matches found:"
sr_title.color = (0.1, 1, 0.1, 1)
else:
sr_title.text = "No results"
sr_title.color = (1, 0, 0, 1)
# This method checks if there is any core DB available.
# If there is, it creates the topics dictionary (topics - button objects).
def build_indices(self):
# If topics dictionary shouldn't be loaded, do nothing.
if not self.must_build_topics:
# Switch screen without updating indicator database.
self.is_manager.current = 'IndexSelectionScreen'
else:
self.topics_dic = {}
# Checks if there is a coreDB available.
try:
set_stored_coredb = open("./DB/core.db", "r")
self.coredb_py = self.string_it(json.load(set_stored_coredb))
set_stored_coredb.close()
# There is no topic at the beginning.
topics_count = 0
# For each topic in core DB..
for topic_numbers in range(1, int(self.coredb_py[2][0]['topics_num'])+1):
# Except topics without Topic note.
if self.coredb_py[2][topic_numbers][0]['note'] != "":
# Count topics.
topics_count += 1
# Grab the topic Info.
topic_note = str(self.coredb_py[2][topic_numbers][0]["note"])
topic_name = str(self.coredb_py[2][topic_numbers][0]["name"])
# Create a new topic button object.
new_button_object = TopicToggleButton(
text=topic_name,
note=topic_note,
on_release=self.add_topic)
# Build each separate dictionary with topic's indices.
indices_dic = {}
for index in range(
1, int(self.coredb_py[2][topic_numbers][0]["indicators_num"])+1):
indices_dic[self.coredb_py[2][topic_numbers][index][1]] = \
[self.coredb_py[2][topic_numbers][index][0],
self.coredb_py[2][topic_numbers][index][2]]
# Store the keys and values from the DB to the cache dictionary.
self.topics_dic[new_button_object] = indices_dic
# Place the button inside the slider.
self.topics_slider_box.add_widget(new_button_object)
# Set the height of the Topics menu based on heights and box padding.
self.topics_slider_box.height = (topics_count * 48) + topics_count + 1
# Topics dictionary should not be loaded again.
self.must_build_topics = False
# Database cannot be updated any more. To update user must restart.
self.is_update_db.disabled = True
# This will build the live Search dictionary.
self.search_dic = {}
for first_depth_key in self.topics_dic:
self.search_dic[first_depth_key.text] = []
for second_depth_key in self.topics_dic[first_depth_key]:
self.search_dic[first_depth_key.text].append(second_depth_key)
# After cache data are ready, switch screen.
self.is_manager.current = 'IndexSelectionScreen'
# If there is no core DB available it prompts for indices update.
except IOError:
self.topics_dic = {}
self.is_manager.current = 'Home'
self.ind_select_icon.state = "normal"
Popup(title='Warning:', content=Label(
text='No Indicator available.\nUpdate the database first.',
font_size=15,
halign="center",
italic=True
), size_hint=(None, None), size=(350, 180)).open()
# Something really unexpected just happened.
except Exception as e:
print "def build_indices(self):", type(e), e.__doc__, e.message
def add_topic(self, *args):
# If topic button is pressed, create index buttons.
if args[0].state == "down":
self.clear_indices_stack()
# Switch topic buttons states.
for button in self.topics_dic.keys():
if button.state == "down" and (button != args[0]):
button.state = "normal"
# Create and add the topic title.
topic = Factory.TopicTitle(text=args[0].text)
self.indices_slider_stack.add_widget(topic)
# Create and add the topic note.
topic_description = Factory.TopicDescription(text=args[0].note)
self.indices_slider_stack.add_widget(topic_description)
# Prepare var for each index button ID
index_btn_id = 0
# Prepare an empty dictionary to hold each index button object and it's ID.
IndexSelection.shown_ind_btns = {}
# Create and add the topic index buttons.
for index in sorted(self.topics_dic[args[0]].keys()):
index_btn_id += 1
btn = IndexToggleButton(
code=self.topics_dic[args[0]][index][0],
text=index,
note=self.topics_dic[args[0]][index][1],
topic=args[0].text,
on_release=self.on_index_selection)
# Place the button in the stacklayout.
self.indices_slider_stack.add_widget(btn)
# Add the button's ID and object button itself in the global "shown_ind_btns" dict.
IndexSelection.shown_ind_btns[index_btn_id] = btn
# Set proper btn backgrounds based on my_indicators.
self.btn_index_background()
# Button is not pressed, which means it self toggled.
else:
self.clear_indices_stack()
class IndexCreation(MouseScreen):
# Link to IndexSelection.
ic_index_selection = ObjectProperty()
# Link to Thematic Button from MainWindow.
ic_thematic_btn = ObjectProperty()
# Link to Thematic Map Designer.
ic_th_designer = ObjectProperty()
# List to show which indicator review is currently loaded.
sorted_indicators = ListProperty()
dropdown_id = ObjectProperty()
dropdown_i = ObjectProperty()
dropdown_r = ObjectProperty()
dropdown_y = ObjectProperty()
all_indicators_data = DictProperty({})
country_list = ListProperty()
country_dict = DictProperty({})
rev_country_dict = DictProperty({})
drawing_data = BooleanProperty(False)
loading_percentage = NumericProperty(0)
formula_items = DictProperty({"last_item": None, "p_group": []})
cim = DictProperty({})
def __init__(self, **kwargs):
# make sure we aren't overriding any important functionality
super(IndexCreation, self).__init__(**kwargs)
self.id_conn = {}
self.rev_id_conn = {}
self.year_row = []
self.data_view_now = []
self.data_queue = None
self.ascending_order_buttons = []
self.descending_order_buttons = []
self.must_draw_data = True
self.loaded_regions = {}
self.loaded_years = []
self.iry_iteration = {"i": [], "r": [], "y": []}
# This method can generate new threads, so that main thread (GUI) won't get frozen.
@staticmethod
def threadonator(*args):
threading.Thread(target=args[0], args=(args,)).start()
# Recursively convert Unicode objects to strings objects.
def string_it(self, obj):
if isinstance(obj, dict):
return {self.string_it(key): self.string_it(value) for key, value in obj.iteritems()}
elif isinstance(obj, list):
return [self.string_it(element) for element in obj]
elif isinstance(obj, unicode):
return obj.encode('utf-8')
else:
return obj
@mainthread
def popuper(self, message, title):
Popup(title=title, content=Label(
text=message,
text_size=(340, 250),
valign="middle",
font_size=15,
halign="center",
italic=True
), size_hint=(None, None), size=(400, 200)).open()
# Function that will run every time mouse is moved.
def on_mouse_pos(self, *args):
if self.toolbox_screenmanager.current == "view_indicators_screen":
for button in self.ascending_order_buttons:
if button.collide_point(*button.to_widget(*args[1])):
button.background_normal = './Sources/ascending_down.png'
else:
button.background_normal = './Sources/ascending_normal.png'
for button in self.descending_order_buttons:
if button.collide_point(*button.to_widget(*args[1])):
button.background_normal = './Sources/descending_down.png'
else:
button.background_normal = './Sources/descending_normal.png'
if self.toolbox_screenmanager.current == "series_selection_screen"\
and self.country_selection_sm.current in self.loaded_regions:
for button in self.loaded_regions[self.country_selection_sm.current]:
if button.collide_point(*button.to_widget(*args[1])):
button.background_normal = button.background_down
else:
button.background_normal = button.normal
if len(self.loaded_years) > 1:
for button in self.loaded_years[-2:]:
if button.collide_point(*button.to_widget(*args[1])):
button.background_normal = button.background_down
else:
button.background_normal = button.normal
if self.toolbox_screenmanager.current == "index_algebra_screen":
for button in self.calculator.children:
if button.collide_point(*button.to_widget(*args[1])):
button.background_normal = button.background_down
else:
button.background_normal = button.normal
if self.ind_calc_btn.collide_point(*self.ind_calc_btn.to_widget(*args[1])):
self.ind_calc_btn.background_normal = self.ind_calc_btn.background_down
else:
self.ind_calc_btn.background_normal = self.ind_calc_btn.normal
@mainthread
def model_toolbox_activator(self, state):
if state:
self.model_toolbox.opacity = 1
else:
self.model_toolbox.opacity = 0
def toolbox_switcher(self, button):
if not self.drawing_data:
self.toolbox_screenmanager.current = button.goto
self.btn_view_indicators.disabled = False
self.btn_series_selection.disabled = False
self.btn_index_algebra.disabled = False
button.disabled = True
def dl_manager(self):
# If togglebutton was pressed and table is currently being loaded, do nothing..
if not self.drawing_data:
# If I have no indicator in my list do nothing but alert.
if not self.ic_index_selection.selected_indices["my_indicators"]:
self.btn_get_indicators.state = "normal"
self.popuper(
'"My Indicators" list should not be empty.\nGo to Indicator Selection.',
'Warning:')
else:
# Clear model's indicator list.
self.indicator_list.clear_widgets()
# Clear current formula in case there is one.
self.my_formula.clear_widgets()
self.btn_view_indicators.disabled = False
self.btn_series_selection.disabled = False
self.btn_index_algebra.disabled = False
self.toolbox_screenmanager.current = "intro"
self.model_toolbox_activator(False)
self.btn_get_indicators.disabled = True
self.downloading_state_icon.source = './Sources/loader.gif'
# Next time btn_view_indicators will be pressed, It will recreate data table.
self.must_draw_data = True
self.threadonator(self.get_indicators)
# ..but re-toggle the button.
else:
self.btn_get_indicators.state = "normal"
@mainthread
def spawn_indicator_widget(self, *args):
# Creation and placement of each widget part.
rvw_widget_main_layout = Factory.RvwWidgetMainLayout()
rvw_widget_head_layout = BoxLayout(orientation="horizontal",
size_hint=(None, None),
size=(262, 70))
rvw_widget_scroll = Factory.RvwWidgetScroll()
rvw_widget_title = Factory.RvwWidgetTitle(text=str(args[0][6]))
rvw_widget_short_id = Factory.RvwWidgetShortID(text=str(args[0][5]))
rvw_widget_foot_layout = Factory.RvwWidgetFootLayout()
rvw_widget_calc1 = Factory.RvwWidgetCalc(width=60)
rvw_widget_calc1_data = Factory.RvwWidgetCalcData(size=(60, 31),
text=str(args[0][0]),
color=(0.9, 0.1, 0.1, 1))
rvw_widget_calc1_desc = Factory.RvwWidgetCalcDesc(size=(60, 32), text="Regions\nW/O Data")
rvw_widget_calc2 = Factory.RvwWidgetCalc(width=90)
rvw_widget_calc2_sum1 = BoxLayout(size_hint=(None, None), size=(90, 15), spacing=5)
rvw_widget_calc2_sum1_desc = Factory.RvwWidgetCalc2Desc(text="60-80:")
rvw_widget_calc2_sum1_data = Factory.RvwWidgetCalc2Data(text=str(args[0][2]))
rvw_widget_calc2_sum2 = BoxLayout(size_hint=(None, None), size=(90, 15), spacing=5)
rvw_widget_calc2_sum2_desc = Factory.RvwWidgetCalc2Desc(text="80-00:")
rvw_widget_calc2_sum2_data = Factory.RvwWidgetCalc2Data(text=str(args[0][3]))
rvw_widget_calc2_sum3 = BoxLayout(size_hint=(None, None), size=(90, 15), spacing=5)
rvw_widget_calc2_sum3_desc = Factory.RvwWidgetCalc2Desc(text="00+:")
rvw_widget_calc2_sum3_data = Factory.RvwWidgetCalc2Data(text=str(args[0][4]))
rvw_widget_calc2_desc = Factory.RvwWidgetCalcDesc(size=(90, 18), text="Total Records")
rvw_widget_calc3 = Factory.RvwWidgetCalc(width=110)
rvw_widget_calc3_data = Factory.RvwWidgetCalcData(size=(110, 31),
text=args[0][1],
color=(0, 0, 0, 1))
rvw_widget_calc3_desc = Factory.RvwWidgetCalcDesc(size=(110, 32),
text="Diachronic\nUnweighted Mean")
rvw_widget_scroll.add_widget(rvw_widget_title)
rvw_widget_head_layout.add_widget(rvw_widget_scroll)
rvw_widget_head_layout.add_widget(rvw_widget_short_id)
rvw_widget_calc1.add_widget(rvw_widget_calc1_data)
rvw_widget_calc1.add_widget(rvw_widget_calc1_desc)
rvw_widget_calc2_sum1.add_widget(rvw_widget_calc2_sum1_desc)
rvw_widget_calc2_sum1.add_widget(rvw_widget_calc2_sum1_data)
rvw_widget_calc2_sum2.add_widget(rvw_widget_calc2_sum2_desc)
rvw_widget_calc2_sum2.add_widget(rvw_widget_calc2_sum2_data)
rvw_widget_calc2_sum3.add_widget(rvw_widget_calc2_sum3_desc)
rvw_widget_calc2_sum3.add_widget(rvw_widget_calc2_sum3_data)
rvw_widget_calc2.add_widget(rvw_widget_calc2_sum1)
rvw_widget_calc2.add_widget(rvw_widget_calc2_sum2)
rvw_widget_calc2.add_widget(rvw_widget_calc2_sum3)
rvw_widget_calc2.add_widget(rvw_widget_calc2_desc)
rvw_widget_calc3.add_widget(rvw_widget_calc3_data)
rvw_widget_calc3.add_widget(rvw_widget_calc3_desc)
rvw_widget_foot_layout.add_widget(rvw_widget_calc1)
rvw_widget_foot_layout.add_widget(rvw_widget_calc2)
rvw_widget_foot_layout.add_widget(rvw_widget_calc3)
rvw_widget_main_layout.add_widget(rvw_widget_head_layout)
rvw_widget_main_layout.add_widget(rvw_widget_foot_layout)
# Finally, add new widget inside model's indicator list.
self.indicator_list.add_widget(rvw_widget_main_layout)
def get_indicators(self, *args):
# Shortcut for "my_indicators".
mi = dict(self.ic_index_selection.selected_indices["my_indicators"])
# Reset indicator data from current database.
self.all_indicators_data = {}
# CleanUP country list and dict's.
self.country_list = []
self.country_dict = {}
self.rev_country_dict = {}
# Reset connection list.
connections = []
# Sort keys for the ID sequence.
self.sorted_indicators = mi.keys()
self.sorted_indicators.sort()
# Number of my indicators.
items = len(self.sorted_indicators)
# Prepare dictionaries to link model's ID's to Indicator names and vice versa.
self.id_conn = {}
self.rev_id_conn = {}
# Characters to use for ID creation
abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# This var will show ID creation sequence.
items_created = 0
# Create short ID's, store link to a dict and prepare each structure. (UPTO 26)
for i in abc:
short_id = "I"+i
# Update ID link's in dictionaries.
self.id_conn[self.sorted_indicators[items_created]] = short_id
self.rev_id_conn[short_id] = self.sorted_indicators[items_created]
# Prepare the basic structure for each indicator.
self.all_indicators_data[short_id] = {}
items_created += 1
if items_created == items:
break
# Prepare new ID creation sequence.
items_created = 0
# Continue creating short ID's, store link to a dict and prepare each structure. (UPTO 676)
if items-26 > 0:
for i in abc:
for j in abc:
short_id = "I"+i+j
# Update ID link dictionary.
self.id_conn[self.sorted_indicators[items_created+26]] = short_id
# Prepare the basic structure for each indicator.
self.all_indicators_data[short_id] = {}
items_created += 1
if items_created == items-26:
break
if items_created == items-26:
break
# Prepare Country Dict's and List and place the list inside all_indicators_data.
for i in range(1, self.ic_index_selection.coredb_py[1][0]["countries_num"]+1):
country = self.ic_index_selection.coredb_py[1][i][1]
self.country_list.append(country)
# Prepare Country dict.
self.country_dict[country] = [self.ic_index_selection.coredb_py[1][i][0],
self.ic_index_selection.coredb_py[1][i][2]]
# Prepare reversed Country dict.
self.rev_country_dict[self.ic_index_selection.coredb_py[1][i][0]] = country
for key in self.all_indicators_data:
self.all_indicators_data[key][country] = {}
# Sort country list.
self.country_list.sort()
try:
for indicator in self.sorted_indicators:
short_id = self.id_conn[indicator]
indicator_address = start_url+countries+indicators+mi[indicator]+"/"+end_url
# print indicator_address # To print the web url
# Define World Bank connection (JSON data).
ind_data_connection = urllib2.urlopen(indicator_address, timeout=120)
# Add current connection to the list with all connections.
connections.append(ind_data_connection)
# Convert JSON data into temp python structure.
ind_data_py = self.string_it(json.load(ind_data_connection))
# This list will store all years with data for each short_id (model indicator).
year_list = []
# For each record in the json file..
for record in range(len(ind_data_py[1])):
country = ind_data_py[1][record]["country"]["value"]
year = int(ind_data_py[1][record]["date"])
value = ind_data_py[1][record]["value"]
if value:
self.all_indicators_data[short_id][country][year] = value
year_list.append(year)
# If year list is not an empty list..
if year_list:
self.all_indicators_data["LastFirst_"+short_id] = [min(year_list),
max(year_list)]
# Begin statistic calculations.
# Track number of countries with no data available for any year.
empty_countries = 0
country_averages = []
plus1960 = 0
plus1980 = 0
plus2000 = 0
for country in self.all_indicators_data[short_id]:
sum_value = 0
available_years = 0
for year, value in self.all_indicators_data[short_id][country].iteritems():
if value:
sum_value += float(value)
available_years += 1
if year < 1980:
plus1960 += 1
elif year < 2000:
plus1980 += 1
else:
plus2000 += 1
if available_years == 0:
empty_countries += 1
else:
country_averages.append(sum_value/available_years)
# Format numbers to be more friendly.
tup = str("%.5G" % (sum(country_averages)/len(country_averages))).partition('E')
mean = (('[size=12]E'.join((tup[0], tup[-1]))+"[/size]")
.replace("[size=12]E[/size]", ""))\
.replace(".", ",")
ind_review = [empty_countries,
mean,
plus1960,
plus1980,
plus2000,
short_id,
indicator]
self.spawn_indicator_widget(ind_review)
self.model_toolbox_activator(True)
except Exception as e:
self.popuper("Could not prepare "+indicator+"\nPlease try again.\n\n"+e.message,
'Warning:')
# Flush sorted_indicators to alert that download did not end with success.
self.sorted_indicators = []
finally:
try:
# Close created connections to WorldBank.
for conn in connections:
conn.close()