Exemplo n.º 1
0
def add_nodes(request):
    """
    Add nodes to a new child phase
    """
    session = DBSession()
    phase = get_object_or_404(Phase, request, ('phase_id', 'id'))
    child_phase = Phase(phase.scenario, phase)
    new_nodes = []
    for feature in request.json_body['features']:
        # assumes point geom
        coords = feature['geometry']['coordinates']
        shp_pt = shapely.geometry.Point(coords[0], coords[1])
        wkb_geom = from_shape(shp_pt, srid=BASE_SRID)
        type_property = feature['properties']['type']
        weight = feature['properties']['weight']
        node_type = get_node_type(type_property, session)
        node = Node(wkb_geom, weight, node_type, child_phase)
        new_nodes.append(node)
    session.add_all(new_nodes)
    session.flush()
    child_phase.create_edges()
    return json_response(
        {'scenario_id': child_phase.scenario_id,
         'phase_id': child_phase.id}
        )
Exemplo n.º 2
0
def show_cumulative_phase_demand_json(phase):
    session = DBSession()
    conn = session.connection()
    sql = text('''
    select nodes.id,
    nodetypes.name,
    nodes.weight,
    st_asgeojson(nodes.point),
    edges.distance 
    from nodes, edges, nodetypes, phase_ancestors
    where nodes.scenario_id = :sc_id and
    nodes.phase_id = phase_ancestors.ancestor_phase_id and
    phase_ancestors.phase_id = :ph_id and
    edges.scenario_id = phase_ancestors.scenario_id and
    edges.phase_id = phase_ancestors.phase_id and
    nodes.id = edges.from_node_id and
    nodes.node_type_id = nodetypes.id and
    nodetypes.name='demand'
    ''')
    rset = conn.execute(sql, sc_id=phase.scenario_id, ph_id=phase.id).fetchall()
    feats = [
        {
        'type': 'Feature',
        'geometry': simplejson.loads(feat[3]),
        'properties': {
            'id':feat[0],
            'type':feat[1],
            'weight':feat[2],
            'distance': feat[4]
            }
        } for feat in rset
    ]
    return json_response({'type': 'FeatureCollection', 'features': feats })
Exemplo n.º 3
0
def get_object_or_404(cls, request, id_fields=('id',)):
    session = DBSession()
    id_vals = [request.matchdict.get(id_fld, None) for id_fld in id_fields]
    # import pdb; pdb.set_trace()
    if id_vals is None:
        raise NameError('You have no fields that match in your request matchdict')
    # import pdb; pdb.set_trace()
    obj = session.query(cls).get(id_vals)
    if obj is not None:
        return obj
    else:
        raise HTTPNotFound('Unable to locate class:%s with ids:%s' % (cls, id_vals))
Exemplo n.º 4
0
def remove_phase(request):
    """
    Remove a phase and all its descendents
    """
    session = DBSession()
    phase = get_object_or_404(Phase, request, ('phase_id', 'id'))

    if phase.is_root():
        raise HTTPBadRequest('Unable to remove a root phase, remove the scenario instead')

    # get all phases that descend from this phase
    phases = phase.get_descendents_query().distinct().order_by(Phase.id.desc())

    """
    phases = session.query(Phase).filter(
            (Phase.scenario_id == phase.scenario_id) &
            (Phase.id == PhaseAncestor.phase_id) &
            (PhaseAncestor.ancestor_phase_id == phase.id) &
            (PhaseAncestor.scenario_id == phase.scenario_id)).distinct().\
                    order_by(Phase.id.desc())
    """

    # needed for referring to parent phase upon return
    scenario_id  = phase.scenario_id
    # get the phase_id of the parent if it exists
    parent_phase_id = session.query(func.max(PhaseAncestor.ancestor_phase_id)).filter(
            (PhaseAncestor.scenario_id == phase.scenario_id) & 
            (PhaseAncestor.phase_id == phase.id) & 
            (PhaseAncestor.ancestor_phase_id < phase.id)).one()[0]
 

    # may want to push this down into Phase object later
    for p in phases:
        session.query(Edge).filter(
                (Edge.scenario_id==p.scenario_id) & 
                (Edge.phase_id==p.id)).delete()
        session.query(Node).filter(
                (Node.scenario_id==p.scenario_id) & 
                (Node.phase_id==p.id)).delete()
        session.query(PhaseAncestor).filter(
                (PhaseAncestor.scenario_id==p.scenario_id) & 
                (PhaseAncestor.phase_id==p.id)).delete()
        session.query(Phase).filter(
                (Phase.scenario_id==p.scenario_id) & 
                (Phase.id==p.id)).delete()
        
    return HTTPFound(location=request.route_url(
        'show-phase', id=scenario_id, phase_id=parent_phase_id))
Exemplo n.º 5
0
def remove_scenario(request):
    session = DBSession()
    sc_pairs = request.params
    sc_dict = sc_pairs.dict_of_lists()
    if (sc_dict.has_key('scenarios')):
        for sid in sc_pairs.dict_of_lists()['scenarios']:
            session.query(Edge).filter(Edge.scenario_id==int(sid)).delete()
            session.query(Node).filter(Node.scenario_id==int(sid)).delete()
            session.query(PhaseAncestor).filter(PhaseAncestor.scenario_id==int(sid)).delete()
            session.query(Phase).filter(Phase.scenario_id==int(sid)).delete()
            session.query(Scenario).filter(Scenario.id==int(sid)).delete()

    return HTTPFound(location=request.route_url('index'))
Exemplo n.º 6
0
def create_supply_nodes(request):
    """
    Create new supply based on distance and re-create the nearest neighbor edges.  
    Create a new child phase of the phase passed in
    Display the new output
    """
    session = DBSession()
    phase = get_object_or_404(Phase, request, ('phase_id', 'id'))
    child_phase = Phase(phase.scenario, phase)
    session.add(child_phase)
    session.flush() #flush this so object has all id's
    distance = float(request.json_body.get('d', 1000))
    num_supply_nodes = int(request.json_body.get('n', 1))

    centroids = child_phase.locate_supply_nodes(distance, num_supply_nodes, session)
    session.add_all(centroids)

    # need to flush so that create_edges knows about new nodes
    session.flush()
    child_phase.create_edges()
    return json_response(
        {'scenario_id': child_phase.scenario_id,
         'phase_id': child_phase.id}
        )
Exemplo n.º 7
0
def index(request):
    session = DBSession()
    sc_dict = {'scenarios': session.query(Scenario).all()}
    return sc_dict 
Exemplo n.º 8
0
def create_scenario(request):
    """
    Bulk load the nodes from the demand and supply csv's
    """
            
    if(request.method=='POST'):
        session = DBSession()
        dbapi_conn = session.connection().connection
        sc = phase = None
        try:
            demand_type = get_node_type('demand', session)
            supply_type = get_node_type('supply', session)
    
            name = request.POST['name']
            # make sure that we have a name
            assert len(name) != 0
    
            sc = Scenario(name)
            session.add(sc)
            session.flush()

            # add the root phase to the scenario
            phase = Phase(sc)
            session.add(phase)
            session.flush()

            demand_file = request.POST['demand-csv']
            supply_file = request.POST['supply-csv']

            tmp_demand_file = os.path.join(
                request.registry.settings['next.temporary_folder'],
                demand_file.filename
                )

            tmp_supply_file = os.path.join(
                request.registry.settings['next.temporary_folder'],
                supply_file.filename
                )

            write_tmp_file(demand_file, tmp_demand_file)
            write_tmp_file(supply_file, tmp_supply_file)

            in_demand_stream = open(tmp_demand_file, 'rU')
            in_supply_stream = open(tmp_supply_file, 'rU')

            import_nodes(dbapi_conn, in_demand_stream, 
                    demand_type.id, sc.id, phase.id)
            import_nodes(dbapi_conn, in_supply_stream, 
                    supply_type.id, sc.id, phase.id)
            
        except Exception as error:
            raise(error)    

            
        # send the user to the run scenario page right now
        # at this point, we should have the scenario/phase, 
        # so create the edges
        # session.commit()
        phase.create_edges()
        return HTTPFound(
            location=request.route_url('show-phase', id=sc.id, phase_id=phase.id))
        
    elif request.method == 'GET':
        return {}
    else:
        raise HTTPForbidden()
Exemplo n.º 9
0
def show_all(request):
    session = DBSession()
    scs = session.query(Scenario).all()
    return json_response({'type': 'FeatureCollection',
                          'features': [sc.to_geojson() for sc in scs]})