示例#1
0
    def get_context_data(self, form, **kwargs):
        """Extension of the get_context_data method of the NamedUrlSessionWizardView.

        Select/process data based on which step of the Form Wizard it's called for.

        - Date: passes existing start_date, end_date values or nothing then template will use min and max.
        - Preview gets all wizard step data gathered so far.
        """
        context = super(BaselineWizardView, self).get_context_data(form=form, **kwargs)

        # All steps:
        if 'edit_scenario' in self.storage.extra_data:
            # if we're in edit mode, let templates know ("Start Over" vs "Cancel Edit" button)
            context['edit_scenario'] = self.storage.extra_data['edit_scenario']

        ######### Start code for specific steps #########

        if self.steps.current == 'location':
            the_request = self.request
            adapter = EMOD_Adapter(self.request.user.username)
            templates = adapter.fetch_template_list()  # get for description

            for key in templates.keys():
                if 'edit_scenario' in self.storage.extra_data \
                        and 'scenario' in self.request.session.keys() \
                        and self.request.session['scenario'].template is not None \
                        and self.request.session['scenario'].template.id is not None \
                        and self.request.session['scenario'].template.id == key:
                    # set the checked option based on the scenario being edited
                    templates[key]['checked'] = 1

                elif 'location' in self.storage.data['step_data'].keys()\
                    and 'location-template_id' in self.storage.data['step_data'][u'location'].keys()\
                    and unicode(key) == \
                        self.storage.data['step_data'][u'location'][u'location-template_id'][0]:
                    # set checked option based on wizard value already saved
                    templates[key]['checked'] = 1

            # For now: limit list to Solomon and Kenya templates
            templates_a = {}
            templates_b = {}
            templates_c = {}
            templates_d = {}
            templates_e = {}

            # reorder the templates so Vietnam 1st, Kenya 2nd, Solomon 3rd
            for key in templates.keys():
                if 'Vietnam' in templates[key]['name']:
                    templates_a.update({key: templates[key]})
            for key in templates.keys():
                if 'Kenya' in templates[key]['name']:
                    templates_b.update({key: templates[key]})
            for key in templates.keys():
                if 'Solomon' in templates[key]['name']:
                    templates_c.update({key: templates[key]})
            for key in templates.keys():
                if 'Uganda' in templates[key]['name']:
                    templates_d.update({key: templates[key]})
            for key in templates.keys():
                if 'Bougainville' in templates[key]['name']:
                    templates_e.update({key: templates[key]})

            pager_size = the_request.POST.get('pager_size')
            if pager_size is None:
                pager_size = 10
            else:
                pager_size = int(pager_size)
            pager_offset = the_request.POST.get('pager_offset')
            if pager_offset is None:
                pager_offset = 0
            else:
                pager_offset = int(pager_offset)

            pager_group = the_request.POST.get('pager_group')
            if pager_group is None:
                pager_group = 0
            else:
                try:
                    pager_group = int(pager_group)
                except TypeError:
                    pager_group = 0

            template_count = len(templates)
            pager_count = template_count / pager_size
            if template_count % pager_size != 0:
                pager_count += 1

            context['pager_offset'] = pager_offset
            context['pager_size'] = pager_size
            context['pager_group'] = pager_group
            context['pager_count'] = range(1, pager_count + 1)
            context['pager_max'] = pager_count
            context['templates_a'] = templates_a
            context['templates_b'] = templates_b
            context['templates_c'] = templates_c
            context['templates_d'] = templates_d
            context['templates_e'] = templates_e
            context['template_count'] = template_count
            context['current_start'] = pager_offset * pager_size + 1
            context['current_stop'] = min(template_count, pager_offset * pager_size + pager_size)
            return context

        if self.steps.current == 'climate':
            my_template = DimTemplate.objects.get(id=self.storage.extra_data['template_id'])
            context['template'] = my_template
            # set up the context to include the files (if any) attached to the scenario
            my_types = [
                'air binary',
                #'air json',
                'humidity binary',
                #'humidity json',
                #'land_temp binary',
                #'land_temp json',
                'rainfall binary']
                #'rainfall json']

            # get scenario files: types/names
            context['climate_files'] = {}
            for my_file in self.request.session['scenario'].get_files():
                # my_file[0] id
                # my_file[1] name
                # my_file[2] type
                if my_file[2] in my_types:
                    context['climate_files'].update({my_file[2].split(' ')[0]: my_file[1]})
            context['climate_files'] = sorted(context['climate_files'].iteritems())
            context['scenario_id'] = self.request.session['scenario'].id

            my_template = DimTemplate.objects.get(id=self.storage.extra_data['template_id'])
            context['template'] = my_template

        if self.steps.current == 'demographic':
            my_template = DimTemplate.objects.get(id=self.storage.extra_data['template_id'])
            context['template'] = my_template

        if self.steps.current == 'species':
            ###
            # Get list of species user can base NEW species creation on (drop-down menu)
            # and to use for adding to a simulation

            # get from template
            try:
                context['species_templates'] = \
                    self.storage.extra_data['scenario_template_config']['parameters']['Vector_Species_Params']
            except KeyError:
                pass

            ###
            # Modify the above list to make the "select from" sources
            species_list = []
            try:
                # turn into objects
                for key, value in context['species_templates'].items():
                    json_string = '{"' + key + '":' + json.dumps(value) + "}"
                    species_list.append(Species(name=key, is_template=1, is_public=0, json=json_string,
                                                created_by=self.request.user))
            except KeyError:
                pass

            # Add in public and user's own custom species objects from DB
            for species in Species.objects.filter(Q(is_public=1) | Q(created_by=self.request.user)):
                species_list.append(species)

            #  This serves as the "from template", "user's custom" and "public" species available
            context['species_list'] = species_list

            ###
            # Populate the already chosen list

            # # Get Baseline or Template ID for passing to SpeciesCreate View
            # #  because wizard storage won't be available in SpeciesCreate View
            my_scenario_id = self.storage.extra_data.get('scenario_id')

            my_species = []
            try:
                my_species.extend(self.request.session['scenario_config']['parameters']['Vector_Species_Names'])
            except (KeyError, TypeError):
                pass

            my_species = sorted(set(my_species))

            context['species_chosen'] = {u'species-species': json.dumps(my_species),
                                         'scenario_id': my_scenario_id,
                                         u'orig_json_obj': ConfigData.objects.filter(
                                         type='JSONConfig', name='default_emod_vector')[0].json}

            context['species_chosen_values'] = \
                json.dumps(self.request.session['scenario_config']['parameters']['Vector_Species_Params'])

        if self.steps.current == 'parasite' or self.steps.current == "vector":
            step_name = self.steps.current
            # build titles for template from name, misc
            my_object = ConfigData.objects.filter(type='JSONConfig', name=step_name)[0]
            context['step_title'] = step_name.title() + " " + my_object.misc.split(":")[1].title()
            context['description'] = my_object.description

            # if the user has not already been through this step
            #  populate the form with the template values.
            if not self.storage.get_step_data(step_name):
                try:
                    context['template_values'] = self.request.session['scenario_config']['parameters']
                except KeyError:
                    pass

        if self.steps.current == 'run':
            form.fields['name'].initial = 'Test Run ' + str(datetime.datetime.now())

        if self.steps.current == 'review':
            # get list of runs for this scenario
            adapter = EMOD_Adapter(self.request.user.username)

            run_list = DimRun.objects.filter(baseline_key=self.request.session['scenario'].id)

            if len(run_list) > 0:
                # sort descending by id (for those old runs that all have the same old time_created
                run_list = sorted(run_list, key=lambda x: x.id, reverse=True)
                # sort descending by time_saved
                run_list = sorted(run_list, key=lambda x: x.time_created, reverse=True)

                # get most recent run, is it still running?
                my_run = run_list[0]

                # check to see if a run is currently running
                status = adapter.run_status(my_run.id)

                if status is None:
                    my_run.my_completed = None
                else:
                    my_run.my_completed = status[0]
                    my_run.my_failed = status[2]
                    if status[0] > 0:
                        context['scenario_has_results'] = 1  # this sets if any of the runs here has results
                    my_run.my_total = status[1]
                    my_run.my_percent_complete = float(status[0]) / float(status[1]) * 100
                    my_run.my_percent_failed = float(status[2]) / float(status[1]) * 100
                    my_run.errors = adapter.fetch_errors(my_run.id)

                # get the results for the last run(s) if it's finished
                context['my_run'] = my_run

                # #6329 - pass in scenario for display of info
                context['scenario'] = self.request.session['scenario']
                my_config = self.request.session['scenario'].get_file_by_type('config').content
                context['Simulation_Duration'] = ast.literal_eval(my_config)['parameters']['Simulation_Duration']

        if self.steps.current == 'run':
            # check for existing runs in this scenario
            if 'scenario' in self.request.session.keys():
                my_runs = DimRun.objects.filter(baseline_key=self.request.session['scenario'].id)
                if len(my_runs) > 0:
                    context['has_runs'] = len(my_runs)
                    # populate the step data so if the skip button is used,
                    # the wizard doesn't skip back to here upon wizard submission (skip isn't a submit, just goto_step)
                    self.storage.set_step_data('run', {u'baseline_wizard_view-current_step': [u'run']})

        return context