def post(self, request, *args, **kwargs):
        """Handle the post of the edit form
        """
        my_form = request.POST
        adapter = EMOD_Adapter(request.user.username)
        my_run = adapter.fetch_runs(run_id=int(kwargs['run_id']))

        metaData = RunMetaData(my_run)
        changed_flag = 0

        for property, value in my_form.iteritems():
            if property in vars(metaData):
                setattr(metaData, property, value)
                changed_flag = 1

        # unchecked checkboxes do not register in the form
        #  so must set to off here if user unchecked is_public
        if 'is_public' not in my_form.keys() and metaData.is_public == 'on':
            setattr(metaData, 'is_public', 'off')
            changed_flag = 1

        # is user has made any changes, save it
        if changed_flag == 1:
            metaData.saveMetaData()

        return redirect("ts_emod_run_metadata_details", run_id=int(kwargs['run_id']))
    def get_context_data(self, **kwargs):
        """Extension of get_context_data
            populate the existing metaData values
        """
        context = super(RunMetadataDetailView, self).get_context_data(**kwargs)
        the_request = self.request

        adapter = EMOD_Adapter(the_request.user.username)
        my_run = adapter.fetch_runs(run_id=int(kwargs['run_id']))

        # if we got here by edit URL, set edit mode.
        if 'mode' in kwargs.keys() and kwargs['mode'] == 'edit' and my_run.baseline_key.user.username == the_request.user.username:
            context['edit'] = True

        try:
            context['metaData'] = RunMetaData(my_run)
        except RuntimeError:
            set_notification('alert-error', '<strong>Error!</strong> Failed to retrieve metadata.', self.request.session)
            scenario_id = my_run.baseline_key
            if scenario_id:
                return redirect("ts_emod_scenario_details", scenario_id=str(scenario_id))
            else:
                return redirect("ts.index")

        return context
示例#3
0
    def get_context_data(self, form, **kwargs):
        context = super(LaunchTool, self).get_context_data(form, **kwargs)

        try:
            context['nav_button'] = self.request.session['emod_nav_button']
        except KeyError:
            pass

        # We need either a run id or scenario id (both really)
        if 'run_id' in kwargs:
            run_id = kwargs['run_id']
            if run_id > 0:
                self.storage.extra_data['emod_launch_run_id'] = run_id
                context['run_named'] = 1
                # get the run's name, to prepopulate the name field
                adapter = EMOD_Adapter(self.request.user.username)
                my_run_id = int(self.storage.extra_data['emod_launch_run_id'])
                my_run = adapter.fetch_runs(scenario_id=-1, run_id=int(my_run_id))
                context['form'].fields['name'].initial = my_run.name
                # save for checking for changes in done method
                self.storage.extra_data['old_run_name'] = my_run.name
        #else:
        # get the specified scenario - error if none specified
        try:
            if 'scenario_id' in kwargs:
                self.storage.extra_data['scenario_id'] = kwargs['scenario_id']
            elif 'scenario_id' not in self.storage.extra_data:
                self.storage.extra_data['error_invalid_id'] = 1
                Exception()
        except KeyError:
            #If there was no scenario id in the url or storage, this wizard is useless... redirect somewhere else
            set_notification('alert-error', 'Error Launching Simulation: Unknown/Invalid run provided. ' +
                                            'Please select a simulation below to launch.', self.request.session)
        return context
示例#4
0
def run_to_scenario(request, run_id):
    """ Function to allow duplication of run DB Objects """
    if not request.user.is_authenticated():
        set_notification('alert-error', '<strong>Error!</strong> Please log in before duplicating. '
                                        'Run was not duplicated.', request.session)
        return redirect("ts_emod_scenario_browse")
    else:
        # Save a copy of the run to Adapter/DW
        try:
            adapter = EMOD_Adapter(request.user.username)
            old_run = adapter.fetch_runs(run_id=int(run_id), as_object=True)
            # create empty scenario
            new_scenario = request.session['scenario'] = EMODBaseline(
                name=old_run.name + ' copy',
                description='Duplicate of ' + old_run.name,
                model=DimModel.objects.get(model='EMOD'),
                user=DimUser.objects.get_or_create(username=request.user.username)[0]
            )

            new_scenario.template = DimTemplate.objects.get(id=old_run.template_key_id)

            new_scenario.model_version = new_scenario.template.model_version

            # get input files for run
            file_dict = old_run.get_input_files()
            new_scenario.add_file_from_string('campaign', 'campaign.json', file_dict['campaign.json'],
                                              description="Added during duplication from run.")
            new_scenario.add_file_from_string('config', 'config.json', file_dict['config.json'],
                                              description="Added during duplication from run.")

            # ToDo: get bin input files for run (from run's template)
            # - for now, user will have to edit, and location step will provide them

            new_scenario.save()

            set_notification('alert-success', '<strong>Success!</strong> The run ' + old_run.name
                                              + ' has been duplicated.', request.session)
        except:
            print 'Error saving the duplicate run to scenario: %s' % old_run.name
            set_notification('alert-error', '<strong>Error!</strong> Error duplicating the run '
                                            + old_run.name + '.', request.session)
            return redirect("ts_emod_scenario_browse")

    return redirect("ts_emod_scenario_details", scenario_id=str(new_scenario.id))
示例#5
0
    def done(self, form_list, **kwargs):
        if 'error_invalid_id' in self.storage.extra_data:
            self.storage.reset()
            set_notification('alert-error', 'Error Launching Simulation: Unknown/Invalid run provided. ' +
                                            'Please select a simulation below to launch.', self.request.session)
            return redirect("ts_emod_scenario_browse")

        if 'scenario_id' in self.storage.extra_data:
            scenario_id = int(self.storage.extra_data['scenario_id'])
        else:
            Exception()

        adapter = EMOD_Adapter(self.request.user.username)

        if 'emod_launch_run_id' in self.storage.extra_data:
            my_run_id = int(self.storage.extra_data['emod_launch_run_id'])
            my_run = adapter.fetch_runs(scenario_id=-1, run_id=int(my_run_id))
            # check for name changes from user
            start_data = self.get_cleaned_data_for_step('start')
            if self.storage.extra_data['old_run_name'] != start_data['name']:
                my_run.name = start_data['name']
                my_run.save()
        else:
            # get the scenario
            self.storage.extra_data['scenario'] = EMODBaseline.from_dw(pk=scenario_id)
            my_config = ast.literal_eval(self.storage.extra_data['scenario'].get_file_by_type('config').content)

            try:
                my_campaign = ast.literal_eval(self.storage.extra_data['scenario'].get_file_by_type('campaign').content)
            except AttributeError:
                # if file list was returned, use last file
                file_list = self.request.session['scenario'].get_file_by_type('campaign')
                my_campaign = ast.literal_eval(file_list[0].content)

            my_campaign_length = len(my_campaign['Events'])

            ###
            # create a new run instance

            if my_campaign_length > 0:
                with_interventions = "with interventions "
            else:
                with_interventions = ""

            my_simulation_duration = my_config['parameters']['Simulation_Duration']

            ## Set the run start_date based on location and config's start_time
            my_start_date = \
                datetime.datetime.strptime(
                    self.storage.extra_data['scenario'].template.climate_start_date,
                    '%Y-%m-%d').date() \
                + datetime.timedelta(days=my_config['parameters']['Start_Time'])

            # Initialize the run
            my_run = adapter.save_run(scenario_id=scenario_id,
                                      template_id=int(self.storage.extra_data['scenario'].template.id),
                                      start_date=my_start_date,
                                      duration=my_simulation_duration,
                                      name=self.get_cleaned_data_for_step('start')['name'],
                                      description='Launch Tool: ' + self.storage.extra_data['scenario'].name
                                                  + ': Run ' + with_interventions + str(datetime.datetime.now()),
                                      location_ndx=self.storage.extra_data['scenario'].template.location_key.id,
                                      timestep_interval=1,
                                      run_id=-1,
                                      as_object=True)

            my_run.baseline_key_id = scenario_id
            my_run.save()

            if settings.DEBUG:
                print "DEBUG: LaunchTool: run id: ", my_run.id

            # add in JCD for config file
            changes = []
            newdict = copy.deepcopy(my_config)

            newdict['config.json/parameters'] = newdict.pop('parameters')
            changes.append(Change.node(name='config.json', node=[newdict], mode='-'))

            # add in JCD for campaign file
            if my_campaign_length > 0:
                newdict = copy.deepcopy(my_campaign)
                newdict['campaign.json/Use_Defaults'] = newdict.pop('Use_Defaults')
                newdict['campaign.json/Events'] = newdict.pop('Events')
                changes.append(Change.node(name='campaign.json', node=[newdict], mode='-'))

            my_run.jcd = JCD.from_changes(changes)
            my_run.save()

        ### Launch the run

        # 5853 - hard-code to 1 for now
        #reps_per_exec = int(self.get_cleaned_data_for_step('start')['reps_per_exec'])
        reps_per_exec = 1

        # If this is a representative based scenario, then set it to non-editable
        representative_scenario = RepresentativeScenario.objects.filter(emod_scenario_id=scenario_id)
        if representative_scenario:
            representative_scenario[0].is_editable = False
            representative_scenario[0].save()

        # submit returns tuple (success, message)
        try:
            status = submit(my_run, user=self.request.user, manifest=True, reps_per_exec=reps_per_exec)

            set_notification('alert-success', '<strong>Success!</strong> Run launched.',
                             self.request.session)
        except (RuntimeError, TypeError, AssertionError), e:
            set_notification('alert-error', '<strong>Error!</strong> ' + str(e.message), self.request.session)