def find_best_segments(cur, stops, shape_ids, route_id=None,<EOL>breakpoints_cache=None):
cache_key = None<EOL>if breakpoints_cache is not None:<EOL><INDENT>cache_key = (route_id, tuple(x['<STR_LIT>'] for x in stops))<EOL>if cache_key in breakpoints_cache:<EOL><INDENT>print('<STR_LIT>')<EOL>return breakpoints_cache[cache_key]<EOL><DEDENT><DEDENT>if route_id is not None:<EOL><INDENT>cur.execute('''<STR_LIT>''',<EOL>(route_id,))<EOL>data = cur.fetchall()<EOL>if not data:<EOL><INDENT>print("<STR_LIT>" % route_id)<EOL>return [], None, None, None<EOL><DEDENT>shape_ids = zip(*data)[<NUM_LIT:0>]<EOL><DEDENT>results = []<EOL>for shape_id in shape_ids:<EOL><INDENT>shape = get_shape_points(cur, shape_id)<EOL>breakpoints, badness = find_segments(stops, shape)<EOL>results.append([badness, breakpoints, shape, shape_id])<EOL>if len(stops) > <NUM_LIT:5> and badness < <NUM_LIT:5>*(len(stops)):<EOL><INDENT>break<EOL><DEDENT><DEDENT>best = np.argmin(zip(*results)[<NUM_LIT:0>])<EOL>badness = results[best][<NUM_LIT:0>]<EOL>breakpoints = results[best][<NUM_LIT:1>]<EOL>shape = results[best][<NUM_LIT:2>]<EOL>shape_id = results[best][<NUM_LIT:3>]<EOL>if breakpoints_cache is not None:<EOL><INDENT>print("<STR_LIT>", cache_key[<NUM_LIT:0>], hash(cache_key[<NUM_LIT:1>:]))<EOL>breakpoints_cache[cache_key] = breakpoints, badness, shape, shape_id<EOL><DEDENT>return breakpoints, badness, shape, shape_id<EOL>
Finds the best shape_id for a stop-sequence.

    This is used in cases like when you have GPS data with a route
    name, but you don't know the route direction.  It tries shapes
    going both directions and returns the shape that best matches.
    Could be used in other cases as well.

    Parameters
    ----------
    cur : sqlite3.Cursor
        database cursor
    stops : list
    shape_ids : list of shape_id:s
    route_id : route_id to search for stops
    breakpoints_cache : dict
        If given, use this to cache results from this function.