Commits

Chris Mutel  committed ccf3c3d

Fix documentation formatting

  • Participants
  • Parent commits 0f67ca2

Comments (0)

Files changed (7)

File brightway2/__init__.py

 # -*- coding: utf-8 -*
 from _config import config
 from meta import databases, methods, mapping, reset_meta
+from serialization import JsonWrapper
 from database import Database
 from method import Method
 from query import Query, Filter, Result

File brightway2/_config.py

     """A singleton that store configuration settings. Default data directory is ``brightway`` in the user's home directory, and is stored as ``config.dir``. Other configuration settings can also be assigned as needed.
 
     Args:
-        *path* (str, optional): The path of the data directory. Must be writeable.
+        * *path* (str, optional): The path of the data directory. Must be writeable.
 
     """
     version = 0.1
     basic_directories = ("processed", "intermediate", "backups", "logs")
 
+    # TODO: Create directory if needed (and basic dirs)
+
     def __init__(self, path=None):
         self.is_temp_dir = False
         self.reset(path)
         if envvar:
             return envvar
         else:
-            return os.path.expanduser("~/brightway2")
+            return os.path.join(os.path.expanduser("~"), "brightway2")
 
     def request_dir(self, dirname):
         """Return ``True`` if directory already exists or can be created."""

File brightway2/database.py

         """Search through the database. See :class:`query.Query` for details."""
         return Query(*queries)(self.load())
 
+    def relabel_data(self, data, new_name):
+        """Relabel database keys and exchanges.
+
+        In a database which internally refer to the same database, update to new database name ``new_name``.
+
+        Needed to copy a database completely or cut out a section of a database.
+
+        For example:
+
+        .. code-block:: python
+
+            data = {
+                ("old and boring", 1):
+                    {"exchanges": [
+                        {"input": ("old and boring", 42),
+                        "amount": 1.0},
+                        ]
+                    },
+                ("old and boring", 2):
+                    {"exchanges": [
+                        {"input": ("old and boring", 1),
+                        "amount": 4.0}
+                        ]
+                    }
+                }
+            print relabel_database(data, "shiny new")
+            >> {
+                ("shiny new", 1):
+                    {"exchanges": [
+                        {"input": ("old and boring", 42),
+                        "amount": 1.0},
+                        ]
+                    },
+                ("shiny new", 2):
+                    {"exchanges": [
+                        {"input": ("shiny new", 1),
+                        "amount": 4.0}
+                        ]
+                    }
+                }
+
+        In the example, the exchange to ``("old and boring", 42)`` does not change, as this is not part of the updated data.
+
+        Args:
+            * *data* (dict): The database data to modify
+            * *new_name* (str): The name of the modified database
+
+        Returns:
+            The modified database
+
+        """
+        def relabel_exchanges(obj, new_name):
+            for e in obj['exchanges']:
+                if e["input"] in data:
+                    e["input"] = (new_name, e["input"][1])
+            return obj
+
+        return dict([((new_name, k[1]), self.relabel_exchanges(v, new_name)) \
+            for k, v in data.iteritems()])
+
     def copy(self, name):
         """Make a copy of the database.
 
         Internal links within the database will be updated to match the new database name.
 
         Args:
-            *name* (str): Name of the new database.
+            * *name* (str): Name of the new database.
 
         """
-        def relabel_exchanges(obj, keys):
-            for e in obj['exchanges']:
-                if e["input"] in data:
-                    e["input"] = (name, e["input"][1])
-            return obj
-
         assert name not in databases, ValueError("This database exists")
-        data = self.load()
-        data = dict([((name, k[1]), relabel_exchanges(v)) for k, v in data.iteritems()])
+        data = self.relabel_data(self.load(), name)
         new_database = Database(name)
         new_database.register(
             format="Brightway2 copy",
             Filepath of backup.
 
         """
-        data = self.load()
-        filepath = os.path.join(config.dir, "backups", self.filename() + \
+        filepath = os.path.join(config.request_dir("backups"), self.filename() + \
             ".%s.backup" % int(time()))
         with open(filepath, "wb") as f:
-            pickle.dump(data, f, protocol=pickle.HIGHEST_PROTOCOL)
+            pickle.dump(self.load(), f, protocol=pickle.HIGHEST_PROTOCOL)
         return filepath
 
     def revert(self, version):
         .. warning:: Reverted changes can be overwritten.
 
         Args:
-            *version* (int): Number of the version to revert to.
+            * *version* (int): Number of the version to revert to.
 
         """
         assert version in [x[0] for x in self.versions()], "Version not found"
         Databases must be registered before data can be written.
 
         Args:
-            *format* (str): Format that the database was converted from, e.g. "Ecospold"
-            *depends* (list): Names of the databases that this database references, e.g. "biosphere"
-            *num_processes* (int): Number of processes in this database.
+            * *format* (str): Format that the database was converted from, e.g. "Ecospold"
+            * *depends* (list): Names of the databases that this database references, e.g. "biosphere"
+            * *num_processes* (int): Number of processes in this database.
 
         """
         assert self.database not in databases
         Raises ``voluptuous.Invalid`` if data does not validate.
 
         Args:
-            *data* (dict): The data, in its processed form.
+            * *data* (dict): The data, in its processed form.
 
         """
         db_validator(data)
         """Serialize data to disk.
 
         Args:
-            *data* (dict): Inventory data
+            * *data* (dict): Inventory data
 
         """
         if self.database not in databases:
         Can also load previous versions of this database's intermediate data.
 
         Args:
-            *version* (int): Version of the database to load. Default is *None*, for the latest version.
+            * *version* (int): Version of the database to load. Default is *None*, for the latest version.
 
         Returns:
             The intermediate data, a dictionary.
         Processed arrays are saved in the ``processed`` directory.
 
         Args:
-            *version* (int, optional): The version of the database to process
+            * *version* (int, optional): The version of the database to process
 
         """
         data = self.load(version)

File brightway2/meta.py

         """Add a set of keys. These keys can already be in the mapping; only new keys will be added.
 
         Args:
-            *keys* (list): The keys to add.
+            * *keys* (list): The keys to add.
 
         """
         index = max(self.data.values())

File brightway2/method.py

     Methods are hierarchally structured, and this structure is preserved in the method name. It is a tuple of strings, like ``('ecological scarcity 2006', 'total', 'natural resources')``.
 
     Args:
-        *method* (tuple): Name of the method to manage. Must be a tuple of strings.
+        * *method* (tuple): Name of the method to manage. Must be a tuple of strings.
 
     """
     def __init__(self, method, *args, **kwargs):
         """Make a copy of the method.
 
         Args:
-            *name* (tuple, optional): Name of the new method.
+            * *name* (tuple, optional): Name of the new method.
 
         """
         name = name or self.method[:-1] + ("Copy of " + self.method[-1],)
         Methods must be registered before data can be written.
 
         Args:
-            *unit* (str): Unit for impact assessment CFs
-            *description* (str): Description
-            num_cfs (int): Number of characterization factors
+            * *unit* (str): Unit for impact assessment CFs
+            * *description* (str): Description
+            * *num_cfs* (int): Number of characterization factors
 
         """
         assert self.method not in methods
         """Validate data. Must be called manually.
 
         Args:
-            *data* (dict): The data, in its processed form.
+            * *data* (dict): The data, in its processed form.
 
         """
         ia_validator(data)
         """Serialize data to disk.
 
         Args:
-            *data* (dict): Inventory data
+            * *data* (dict): Inventory data
 
         """
         if self.method not in methods:

File brightway2/query.py

     The dataset can also be sorted, using ``sort(field)``; the underlying data is then a ``collections.OrderedDict``.
 
     Args:
-        *result* (dict): The filtered dataset.
+        * *result* (dict): The filtered dataset.
 
     """
     def __init__(self, result):
         """Sort the filtered dataset. Operates in place; does not return anything.
 
         Args:
-            *field* (str): The key used for sorting.
-            *reverse* (bool, optional): Reverse normal sorting order.
+            * *field* (str): The key used for sorting.
+            * *reverse* (bool, optional): Reverse normal sorting order.
 
         """
         self.result = collections.OrderedDict(sorted(self.result.iteritems(),
     Filters are applied by calling the ``Query`` object, and passing the dataset to filter as the argument. Calling a ``Query`` with some data returns a ``Result`` object with the filtered dataset.
 
     Args:
-        *filters* (filters): One or more ``Filter`` objects.
+        * *filters* (filters): One or more ``Filter`` objects.
 
     """
     def __init__(self, *filters):
         * Category (a list of categories and subcategories) includes *foo*: ``Filter("category", "in", "foo")``
 
     Args:
-        *key* (str): The field to filter on.
-        *function* (str or object): One of the pre-defined filters, or a callable object.
-        *value* (object): The value to test against.
+        * *key* (str): The field to filter on.
+        * *function* (str or object): One of the pre-defined filters, or a callable object.
+        * *value* (object): The value to test against.
 
     Returns:
         A ``Result`` object which wraps a new data dictionary.

File brightway2/serialization.py

         """Method to do the actual serialization. Can be replaced with other serialization formats.
 
         Args:
-            *filepath* (str, optional): Provide an alternate filepath (e.g. for backup).
+            * *filepath* (str, optional): Provide an alternate filepath (e.g. for backup).
 
         """
         JsonWrapper.dump(self.pack(self.data), filepath or self._filepath)