Пример #1
0
def fetch_cube(dataset, dimensions, weight=None, filter=None, **measures):
    """Return a shoji.View containing a crunch:cube.

    The dataset entity is used to look up its views.cube URL.
    The dimensions must be a list of either strings, which are assumed to be
    URL's of variable Entities to be fetched and analyzed according to type,
    or objects, which are assumed to be complete variable expressions.
    The weight, if sent, should be the URL of a valid weight variable
    If applying a filter, it should be a filter expression or filter URL.

    >>> dataset = session.site.datasets.by('name')['my dataset'].entity
    >>> variables = dataset.variables.by('alias')
    >>> dimensions = [
    ... {"each": variables['CA'].entity_url},
    ...     {"variable": variables['CA'].entity_url}
    ... ]
    >>> weight = variables['weight_var'].entity_url
    >>> count = {
    ...     "function": "cube_count",
    ...     "args": []
    ... }
    >>> filter = {
    ...     "function": "!=",
    ...     "args": [
    ...         {"variable": variables['categorical_var'].entity_url},
    ...         {"value": 3},
    ...     ]
    ... }
    >>> fetch_cube(dataset, dimensions, weight=weight, filter=filter, count=count)

    """
    dims = DimensionsPreparer(dataset).prepare_dimensions(dimensions)
    cube_query = elements.JSONObject(dimensions=dims, measures=measures)

    if weight is not None:
        cube_query['weight'] = weight

    params = {"query": cube_query.json}
    if filter is not None:
        params['filter'] = elements.JSONObject(filter).json

    return dataset.session.get(dataset.views.cube, params=params).payload
Пример #2
0
    def by(self, attr):
        """Return the Tuples of self.index indexed by the given 'attr' instead.

        If a given Tuple does not contain the specified attribute,
        it is not included. If more than one does, only one will be
        included (which one is undefined).

        The specified attr is not popped from the Tuple; it is merely
        copied to the output keys. Due to restrictions on Python dicts,
        specifying attrs which are not hashable will raise an error.
        """
        return elements.JSONObject(**dict(
            (tupl[attr], tupl) for tupl in six.itervalues(self.index)
            if attr in tupl))
Пример #3
0
def cast(variable, type, format=None, offset=None, resolution=None):
    """Alter the given variable Entity to a new type.

    Various parameters may need to be sent to properly convert from one type
    to another. Datetime is particularly demanding.
    """
    payload = elements.JSONObject(cast_as=type)
    if format is not None:
        payload['format'] = format
    if offset is not None:
        payload['offset'] = offset
    if resolution is not None:
        payload['resolution'] = resolution

    return variable.cast.post(data=payload.json)
Пример #4
0
def fetch_cube(dataset, dimensions, weight=None, **measures):
    """Return a shoji.View containing a crunch:cube.

    The dataset entity is used to look up its views.cube URL.
    The dimensions must be a list of either strings, which are assumed to be
    URL's of variable Entities to be fetched and analyzed according to type,
    or objects, which are assumed to be complete variable expressions.
    """
    dims = []
    for d in dimensions:
        if isinstance(d, dict):
            # This is already a Crunch expression.
            dims.append(d)
        elif isinstance(d, six.string_types):
            ref = {'variable': d}
            # A URL of a variable entity. GET it to find its type.
            v = dataset.session.get(d).payload
            if v.body.type == "numeric":
                dims.append({"function": "bin", "args": [ref]})
            elif v.body.type == "datetime":
                rollup_res = v.body.view.get("rollup_resolution", None)
                dims.append({
                    "function": "rollup",
                    "args": [ref, {
                        "value": rollup_res
                    }]
                })
            elif v.body.type == "categorical_array":
                dims.append(ref)
                dims.append({"each": d})
            elif v.body.type == "multiple_response":
                dims.append({"function": "selected_array", "args": [ref]})
                dims.append({"each": d})
            else:
                dims.append(ref)
        else:
            raise TypeError(
                "dimensions must be URL strings or Crunch expression objects.")

    q = elements.JSONObject(dimensions=dims, measures=measures)
    if weight is not None:
        q['weight'] = weight

    return dataset.session.get(dataset.views.cube, params={
        "query": q.json
    }).payload
Пример #5
0
def fetch_cube(dataset, dimensions, weight=None, filter=None, **measures):
    """Return a shoji.View containing a crunch:cube.

    The dataset entity is used to look up its views.cube URL.
    The dimensions must be a list of either strings, which are assumed to be
    URL's of variable Entities to be fetched and analyzed according to type,
    or objects, which are assumed to be complete variable expressions.
    The weight, if sent, should be the URL of a valid weight variable
    If applying a filter, it should be a filter expression or filter URL.

    >>> dataset = session.site.datasets.by('name')['my dataset'].entity
    >>> variables = dataset.variables.by('alias')
    >>> dimensions = [
    ... {"each": variables['CA'].entity_url},
    ...     {"variable": variables['CA'].entity_url}
    ... ]
    >>> weight = variables['weight_var'].entity_url
    >>> count = {
    ...     "function": "cube_count",
    ...     "args": []
    ... }
    >>> filter = {
    ...     "function": "!=",
    ...     "args": [
    ...         {"variable": variables['categorical_var'].entity_url},
    ...         {"value": 3},
    ...     ]
    ... }
    >>> fetch_cube(dataset, dimensions, weight=weight, filter=filter, count=count)

    """
    dims = []
    for d in dimensions:
        if isinstance(d, dict):
            # This is already a Crunch expression.
            dims.append(d)
        elif isinstance(d, six.string_types):
            ref = {'variable': d}
            # A URL of a variable entity. GET it to find its type.
            v = dataset.session.get(d).payload
            if v.body.type == "numeric":
                dims.append({"function": "bin", "args": [ref]})
            elif v.body.type == "datetime":
                rollup_res = v.body.view.get("rollup_resolution", None)
                dims.append({
                    "function": "rollup",
                    "args": [ref, {
                        "value": rollup_res
                    }]
                })
            elif v.body.type == "categorical_array":
                dims.append({"each": d})
                dims.append(ref)
            elif v.body.type == "multiple_response":
                dims.append({"each": d})
                dims.append({"function": "as_selected", "args": [ref]})
            else:
                dims.append(ref)
        else:
            raise TypeError(
                "dimensions must be URL strings or Crunch expression objects.")

    q = elements.JSONObject(dimensions=dims, measures=measures)
    if weight is not None:
        q['weight'] = weight

    params = {"query": q.json}
    if filter is not None:
        params['filter'] = elements.JSONObject(filter).json

    return dataset.session.get(dataset.views.cube, params=params).payload