[ 
https://issues.apache.org/jira/browse/BEAM-4391?focusedWorklogId=121196&page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel#worklog-121196
 ]

ASF GitHub Bot logged work on BEAM-4391:
----------------------------------------

                Author: ASF GitHub Bot
            Created on: 10/Jul/18 04:10
            Start Date: 10/Jul/18 04:10
    Worklog Time Spent: 10m 
      Work Description: aaltay commented on a change in pull request #5736: 
[BEAM-4391] Example of distributed optimization
URL: https://github.com/apache/beam/pull/5736#discussion_r201212249
 
 

 ##########
 File path: 
sdks/python/apache_beam/examples/complete/distribopt/distribopt/distribopt.py
 ##########
 @@ -0,0 +1,349 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""
+Example illustrating the use of Apache Beam for distributing optimization 
tasks.
+Running this example requires NumPy and SciPy
+"""
+import argparse
+import logging
+import string
+import uuid
+from collections import defaultdict
+
+import numpy as np
+from scipy.optimize import minimize
+
+import apache_beam as beam
+from apache_beam import pvalue
+from apache_beam.options.pipeline_options import PipelineOptions
+from apache_beam.options.pipeline_options import SetupOptions
+
+
+class Simulator(object):
+  """
+  Greenhouse simulation
+
+  Disclaimer: this code is an example and does not correspond to any real 
greenhouse simulation.
+  """
+
+  def __init__(self, quantities):
+    super(Simulator, self).__init__()
+    self.quantities = np.atleast_1d(quantities)
+
+    self.A = np.array([[3.0, 10, 30],
+                       [0.1, 10, 35],
+                       [3.0, 10, 30],
+                       [0.1, 10, 35]])
+
+    self.P = 1e-4 * np.array([[3689, 1170, 2673],
+                              [4699, 4387, 7470],
+                              [1091, 8732, 5547],
+                              [381, 5743, 8828]])
+
+    a0 = np.array([1.0, 1.2, 3.0, 3.2])
+    coeff = np.sum(np.cos(np.dot(np.atleast_2d(a0).T, self.quantities[None, 
:])), axis=1)
+    self.alpha = coeff / np.sum(coeff)
+
+  def simulate(self, xc):
+    # Map the input parameter to a cost for each crop.
+    f = -np.sum(self.alpha * np.exp(-np.sum(self.A * np.square(xc - self.P), 
axis=1)))
+    return np.square(f) * np.log(self.quantities)
+
+
+class CreateGrid(beam.PTransform):
+  """
+  A transform for generating the mapping grid.
+  """
+
+  class PreGenerateMappings(beam.DoFn):
+    """
+    ParDo implementation which splits of 2 records and generated a sub grid.
+
+    This facilitates parallellization of the grid generation.
+    Emits both the PCollection representing the subgrid, as well as the list
+    of remaining records. Both serve as an input to GenerateMappings
+    """
+
+    def process(self, element):
+      records = list(element[1])
+      # Split of 2 crops and pre-generate all combinations to facilitate 
parallellism
+      # No point splitting of a crop which can only be created in 1 greenhouse,
+      # split of crops with highest number of options.
+      best_split = np.argsort([-len(rec['transport_costs']) for rec in 
records])[:2]
+      rec1 = records[best_split[0]]
+      rec2 = records[best_split[1]]
+
+      # Generate & emit all combinations
+      for a in rec1['transport_costs']:
+        if a[1]:
+          for b in rec2['transport_costs']:
+            if b[1]:
+              combination = [(rec1['crop'], a[0]), (rec2['crop'], b[0])]
+              yield pvalue.TaggedOutput('splitted', combination)
+
+      # Pass on remaining records
+      remaining = [rec for i, rec in enumerate(records) if i not in best_split]
+      yield pvalue.TaggedOutput('combine', remaining)
+
+  class GenerateMappings(beam.DoFn):
+    """
+    ParDo implementation to generate all possible assignments of crops to 
greenhouses.
+
+    Input: dict with crop, quantity and transport_costs keys, e.g.,
+    {
+        'crop': 'OP009',
+        'quantity': 102,
+        'transport_costs': [('A', None), ('B', 3), ('C', 8)]
+    }
+
+    Output: tuple (mapping_identifier, {crop -> greenhouse})
+    """
+
+    @staticmethod
+    def _coordinates_to_greenhouse(coordinates, greenhouses, crops):
+      # Map the grid coordinates back to greenhouse labels
+      arr = []
+      for coord in coordinates:
+        arr.append(greenhouses[coord])
+      return dict(zip(crops, np.array(arr)))
+
+    def process(self, element, records):
+      # Generate available greenhouses and grid coordinates for each crop.
+      grid_coordinates = []
+      for rec in records:
+        # Get indices for available greenhouses (w.r.t crops)
+        filtered = [i for i, available in enumerate(rec['transport_costs']) if 
available[1]]
+        grid_coordinates.append(filtered)
+
+      # Generate all mappings and .
+      grid = np.vstack(map(np.ravel, np.meshgrid(*grid_coordinates))).T
+      crops = [rec['crop'] for rec in records]
+      greenhouses = [rec[0] for rec in records[0]['transport_costs']]
+      mappings = []
+      for point in grid:
+        # translate back to greenhouse label
+        mapping = self._coordinates_to_greenhouse(point, greenhouses, crops)
+        assert all(rec[0] not in mapping for rec in element)
+        # include the incomplete mapping of 2 crops
+        mapping.update(element)
+        # include identifier
+        yield (uuid.uuid4().hex, mapping)
+
+  def expand(self, records):
+    o = (
+        records
+        | 'pair one' >> beam.Map(lambda x: (1, x))
+        | 'group all records' >> beam.GroupByKey()
+        | 'split one of' >> beam.ParDo(self.PreGenerateMappings())
+                              .with_outputs('splitted', 'combine')
+    )
+
+    # Create mappings, and prevent fusion (this limits the parallelization
+    # in the optimization step)
+    mappings = (
+        o.splitted
+        | 'create mappings' >> beam.ParDo(self.GenerateMappings(), 
pvalue.AsSingleton(o.combine))
+        | 'prevent fusion' >> beam.Reshuffle()
+    )
+
+    return mappings
+
+
+class OptimizeGrid(beam.PTransform):
+  """
+  A transform for optimizing all greenhouses of the mapping grid.
+  """
+
+  class CreateOptimizationTasks(beam.DoFn):
+    """
+    Create tasks for optimization.
+
+    Input: (mapping_identifier, {crop -> greenhouse})
+    Output: ((mapping_identifier, greenhouse), [(crop, quantity),...])
+    """
+
+    def process(self, element, quantities):
+      mapping_identifier, mapping = element
+
+      # Create (crop, quantity) lists for each greenhouse
+      greenhouses = defaultdict(list)
+      for crop, greenhouse in mapping.iteritems():
+        quantity = quantities[crop]
+        greenhouses[greenhouse].append((crop, quantity))
+
+      # Create input for OptimizeProductParameters
+      for greenhouse, crops in greenhouses.iteritems():
+        key = (mapping_identifier, greenhouse)
+        yield (key, crops)
+
+  class OptimizeProductParameters(beam.DoFn):
+    """
+    Solve the optimization task to determine optimal production parameters.
+    Input: ((mapping_identifier, greenhouse), [(crop, quantity),...])
+    Two outputs:
+        - solution: (mapping_identifier, (greenhouse, [production parameters]))
+        - costs: (crop, greenhouse, mapping_identifier, cost)
+    """
+
+    @staticmethod
+    def _optimize_production_parameters(sim):
+      # setup initial starting point & bounds
+      x0 = 0.5 * np.ones(3)
+      bounds = zip(np.zeros(3), np.ones(3))
+
+      # Run L-BFGS-B optimizer
+      result = minimize(lambda x: np.sum(sim.simulate(x)), x0, bounds=bounds)
+      return result.x.tolist(), sim.simulate(result.x)
+
+    def process(self, element):
+      mapping_identifier, greenhouse = element[0]
+      crops, quantities = zip(*element[1])
+      sim = Simulator(quantities)
+      optimum, costs = self._optimize_production_parameters(sim)
+      solution = (mapping_identifier, (greenhouse, optimum))
+      yield pvalue.TaggedOutput('solution', solution)
+      for crop, cost, quantity in zip(crops, costs, quantities):
+        costs = (crop, greenhouse, mapping_identifier, cost * quantity)
+        yield pvalue.TaggedOutput('costs', costs)
+
+  def expand(self, inputs):
+    mappings, quantities = inputs
+    opt = (
+        mappings
+        | 'optimization tasks' >> beam.ParDo(self.CreateOptimizationTasks(), 
pvalue.AsDict(quantities))
+        | 'optimize' >> 
beam.ParDo(self.OptimizeProductParameters()).with_outputs('costs', 'solution')
+    )
+    return opt
+
+
+class CreateTransportData(beam.DoFn):
+  """
+  Transform records to pvalues ((crop, greenhouse), transport_cost)
 
 Review comment:
   What does 'Transform records to pvalues' mean?

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Issue Time Tracking
-------------------

    Worklog Id:     (was: 121196)

> Example of distributed optimization
> -----------------------------------
>
>                 Key: BEAM-4391
>                 URL: https://issues.apache.org/jira/browse/BEAM-4391
>             Project: Beam
>          Issue Type: New Feature
>          Components: examples-python
>            Reporter: Joachim van der Herten
>            Assignee: Joachim van der Herten
>            Priority: Minor
>          Time Spent: 1h 50m
>  Remaining Estimate: 0h
>
> Currently, we are writing a blogpost on using the Beam Python SDK for solving 
> distributed optimization tasks. It will include an example of a optimization 
> problem with both discrete and continuous parameters, which is then solved 
> using Apache Beam. 



--
This message was sent by Atlassian JIRA
(v7.6.3#76005)

Reply via email to