Esempio n. 1
0
 def new(self, format='html'):
     'GET /scenarios/new: Show form to create a new item'
     # If the user is not logged in,
     if not h.isPerson():
         # Redirect to login
         return redirect(url('person_login', targetURL=h.encodeURL(h.url('new_scenario'))))
     # Make sure that the requested metric model exists
     metricModelNames = metric.getModelNames()
     metricModelName = request.GET.get('metricModel')
     if metricModelName not in metricModelNames:
         metricModelName = metricModelNames[0]
     c.metricModel = metric.getModel(metricModelName)
     c.metricConfiguration = {}
     # Make sure that the requested network model exists
     networkModelNames = network.getModelNames()
     networkModelName = request.GET.get('networkModel')
     if networkModelName not in networkModelNames:
         networkModelName = networkModelNames[0]
     c.networkModel = network.getModel(networkModelName)
     c.networkConfiguration = {}
     # Render form
     c.scenario = None
     return render('/scenarios/new.mako')
Esempio n. 2
0
 def create(self):
     'POST /scenarios: Create a new item'
     # Initialize
     personID = h.getPersonID()
     if not personID:
         return redirect(url('person_login', targetURL=h.encodeURL(h.url('new_scenario'))))
     # Load
     try:
         demographicDatabase_h = int(request.POST.get('demographicDatabase_h', 0))
     except ValueError:
         demographicDatabase_h = 0
     if not demographicDatabase_h and 'demographicDatabase' not in request.POST:
         return cjson.encode(dict(isOk=0, message='The demographicDatabase field is required'))
     scenarioName = request.POST.get('scenarioName') or 'Untitled'
     try:
         scenarioScope = int(request.POST.get('scenarioScope', model.scopePrivate))
     except ValueError:
         scenarioScope = model.scopePrivate
     metricModelName = request.POST.get('metricModelName', metric.getModelNames()[0])
     networkModelName = request.POST.get('networkModelName', network.getModelNames()[0])
     callbackURL = request.POST.get('callbackURL')
     # Create scenario
     scenario = model.Scenario(personID, scenarioName, scenarioScope)
     Session.add(scenario)
     Session.commit()
     scenarioFolder = scenario.getFolder()
     if os.path.exists(scenarioFolder):
         shutil.rmtree(scenarioFolder)
     store.makeFolderSafely(scenarioFolder)
     # If the user is using an existing demographicDatabase,
     if demographicDatabase_h:
         # Copy source in case it is deleted
         sourceScenario = Session.query(model.Scenario).get(demographicDatabase_h)
         sourceScenarioFolder = sourceScenario.getFolder()
         demographicFileName = sourceScenario.input['demographic file name']
         demographicPath = os.path.join(scenarioFolder, demographicFileName)
         shutil.copyfile(os.path.join(sourceScenarioFolder, demographicFileName), demographicPath)
     # If the user is uploading a new demographicDatabase,
     else:
         # Save original demographicDatabase in case the user wants it later
         demographicDatabase = request.POST['demographicDatabase']
         demographicFileExtension = os.path.splitext(demographicDatabase.filename)[1]
         demographicFileName = 'demographics' + demographicFileExtension
         demographicPath = os.path.join(scenarioFolder, demographicFileName)
         shutil.copyfileobj(demographicDatabase.file, open(demographicPath, 'wb'))
         demographicDatabase.file.close()
     # Store input
     configurationByName = extractConfigurationByName(request.POST, scenarioFolder)
     scenario.input = {
         'demographic file name': str(demographicFileName),
         'metric model name': metricModelName,
         'metric configuration': configurationByName.get('metric', {}),
         'network model name': networkModelName,
         'network configuration': configurationByName.get('network', {}),
         'callback url': callbackURL,
         'host url': request.host_url, 
     }
     Session.commit()
     store.zipFolder(scenarioFolder + '.zip', scenarioFolder)
     # Redirect
     redirect(url('scenario', id=scenario.id))
Esempio n. 3
0
                lines.append('Derivatives\n')
                lines.extend('- :ref:`%s > %s <%s>`\n' % (x.section, x.option, variable_store.formatLabel(x)) for x in derivativesByVariable[variable])
            # Output code
            lines.append('\n::\n\n%s\n\n\n' % '\n'.join('    ' + x for x in inspect.getsource(variable).splitlines()))
        # For each variable sorted by option,
        for variable in sorted(variables, key=lambda x: x.option):
            # Append long alias, short alias, units
            rows.append((':ref:`%s > %s <%s>`' % (variable.section, variable.option, variable_store.formatLabel(variable)), ' '.join(variable.aliases or []), variable.units))
    # Return
    return roots, lines, rows


# If we are running the script from the command-line,
if __name__ == '__main__':
    # For each metric model,
    for metricModelName in metric.getModelNames():
        # Load metric model
        metricModel = metric.getModel(metricModelName)
        metricRoots, metricLines, metricRows = generateDocumentation(metricModel)
        # Save and close
        referenceFile = open(os.path.join(script_process.basePath, 'docs/metric-%s.rst' % metricModelName), 'wt')
        referenceFile.write(formatHeader('Metric Model %s' % metricModelName, '='))
        for root in sorted(metricRoots, key=lambda x: metricModel.roots.index(x)):
            referenceFile.write('- :ref:`%s`\n' % variable_store.formatLabel(root))
        referenceFile.write('\n\n' + 'You can override the value of any variable in the model on a node-by-node basis.  To perform a node-level override, use the aliases in the following table as additional columns in your spreadsheet or fields in your shapefile.  Both long and short aliases are recognized.')
        referenceFile.write('\n\n' + formatTable(['Long alias', 'Short alias', 'Units'], metricRows))
        referenceFile.write('\n\n' + '\n'.join(metricLines))
        referenceFile.close()
    # For each network model,
    for networkModelName in network.getModelNames():
        # Load network model
# Import custom modules
from np.lib import dataset_store, metric, network, variable_store as VS

"""
Utility to run a full scenario on a set of demand nodes (running the
metric model, network model, aggregations and outputting the resulting
dataset).  

This is useful for getting rapid feedback on demand and model changes.
(i.e. you don't need to deploy the web-site to run this)
"""

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description="Run NetworkPlanner Scenario")
    parser.add_argument('metric_model_name', choices=metric.getModelNames(),
                        help="metric model definition to run")
    parser.add_argument('metric_model_params', type=argparse.FileType('r'),
                        help="model parameters json file")
    parser.add_argument('network_model_name', choices=network.getModelNames(),
                        help="network model definition to run")
    parser.add_argument('network_model_params', type=argparse.FileType('r'),
                        help="model parameters json file")
    parser.add_argument('output_path', help="directory where outputs will be placed")
    parser.add_argument('input_nodes_file', help="csv file of nodes (lat,lon,population,...)")
    parser.add_argument("-t", "--header-type", 
                        choices=[VS.HEADER_TYPE_SECTION_OPTION, 
                                 VS.HEADER_TYPE_ALIAS], 
                        default=VS.HEADER_TYPE_ALIAS,
                        help="the output file header field name type")