From fb7e51ab031d3bd31c0dc905e3b7a89f9a21f8ad Mon Sep 17 00:00:00 2001
From: Stephan Seitz <stephan.seitz@fau.de>
Date: Tue, 6 Aug 2019 13:52:22 +0200
Subject: [PATCH] Add AssignmentCollection.has_exclusive_writes

An assumption of pystencils is that output stencils never overlap.
This allows massive parallelization without race conditions or atomics.

When I use my autodiff transformations I use this condition to check
whether the assumption still hold for the backward assignments.
---
 pystencils/simp/assignment_collection.py | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/pystencils/simp/assignment_collection.py b/pystencils/simp/assignment_collection.py
index c5a18379..3274476e 100644
--- a/pystencils/simp/assignment_collection.py
+++ b/pystencils/simp/assignment_collection.py
@@ -3,6 +3,7 @@ from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Set,
 
 import sympy as sp
 
+import pystencils
 from pystencils.assignment import Assignment
 from pystencils.sympyextensions import count_operations, fast_subs, sort_assignments_topologically
 
@@ -346,6 +347,25 @@ class AssignmentCollection:
     def __iter__(self):
         return self.main_assignments.__iter__()
 
+    def has_exclusive_writes(self):
+        """
+        Simple check for exclusive (non-overlapping) writes.
+        I.e. AssignmentCollection can be executed safely in parallel without caring about race conditions.
+        """
+
+        assignments = self.main_assignments
+        write_field_accesses = [a.lhs for a in assignments if isinstance(a.lhs, pystencils.Field.Access)]
+
+        exclusive_writes = set()
+        for a in write_field_accesses:
+
+            if (a.field, a.index) in exclusive_writes:
+                return False
+            else:
+                exclusive_writes.add((a.field, a.index))
+
+        return True
+
     @property
     def main_assignments_dict(self):
         return {a.lhs: a.rhs for a in self.main_assignments}
-- 
GitLab