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

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_r201211811
 
 

 ##########
 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.
 
 Review comment:
   You can start pydoc comments in the first line with """. (For examples see: 
https://github.com/apache/beam/blob/master/sdks/python/apache_beam/examples/complete/tfidf.py#L52)

----------------------------------------------------------------
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: 121193)
    Time Spent: 1.5h  (was: 1h 20m)

> 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: 1.5h
>  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