Skip to content

Template difference with tests #60

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 32 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
608faee
Add operation of Template Difference
zorandir Feb 21, 2016
13bbfdf
Merge branch 'color-blind-adt' into template-difference
zorandir Mar 25, 2016
3305443
Fix TemplateDifference
zorandir Mar 26, 2016
dea04e1
Add *.iml to .gitignore
zorandir Mar 26, 2016
f00df70
Create Difference/Common.wl
zorandir Mar 26, 2016
9a0bb9b
Create some tests to TemplateDifference.m
zorandir Mar 26, 2016
1408f7d
Make TemplateDifference works with adt; Create RawDifference
zorandir Mar 26, 2016
ebc15a6
Merge branch 'master' into template-difference
zorandir Mar 27, 2016
ce0d8b4
Remove // notation
zorandir Apr 2, 2016
5b50711
Removed some commented codes
zorandir Apr 2, 2016
0915277
Using BuildTemplate instead of the explicit templates
zorandir Apr 2, 2016
76136d0
Change usage of DifferenceReplacementRules; Remove unnecessary map
zorandir Apr 3, 2016
2fe266a
Refactoring MinimizeSets[subSets_List]
zorandir Apr 3, 2016
f5c6bec
Merge branch 'master' into template-difference
zorandir Apr 15, 2016
47f087f
Using PrintTestResults[] in tests
zorandir Apr 15, 2016
c805ed1
Remove Test.m and add a test in Tests/Basic.m
zorandir Apr 15, 2016
fa35caf
Remove OldExceptionTemplates and refactory in ExceptionTemplates
zorandir Apr 15, 2016
3b81edf
Refactor of MinimizeSets[]
zorandir Apr 16, 2016
538a1b1
Changed TemplateDifference::imprisonmentExpressions message
zorandir Apr 16, 2016
bea7b82
Removing function RemoveContainedSubSets
zorandir Apr 21, 2016
f10b8bf
Refactor SubSetsToBooleanExpression
mverardo Apr 22, 2016
f7022cc
Refactoring MinimizeSets
zorandir May 11, 2016
b0cfbf8
Refactoring in ExceptionTemplates.m
zorandir May 13, 2016
258e102
Fix imports in RawDifference
zorandir May 14, 2016
c06342c
Add Tests to ExpandVar[]
zorandir May 14, 2016
f32050c
Testing new RawDifference[]
zorandir May 15, 2016
6cefff3
Fix totalistic template
zorandir May 20, 2016
8369dfa
tests in difference
zorandir May 20, 2016
7311e09
Add Tests to TemplateDifference.wl
zorandir May 23, 2016
33eb8fd
Fix and tests
zorandir Jul 18, 2016
2afda86
Merge branch 'master' into template-difference-tests
zorandir Aug 12, 2016
43604e7
Commented test in large spaces
zorandir Aug 15, 2016
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ TemplateOperations/*.nb
TemplateGeneration/*.nb
.DS_Store
.idea/*
*.iml
61 changes: 34 additions & 27 deletions Basic.wl
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@

BeginPackage["CATemplates`Basic`"];


BooleanFromRule::usage="Transforms a rule into boolean form.";
ConjunctionFromRuleSet::usage="Transforms a rule set into a boolean conjunction";
DNFFromRuleSet::usage="Transforms a set of set of rules into a DNF form boolean expression";
MinimizedRuleSets::usage = "Minimize a subset boolean expression";
Copy link
Owner

@mverardo mverardo Aug 16, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid adding functions to Basic.
#59 removes this namespace and we are gonna have conflicts.
If these functions are only used on ExceptionTemplates, you can leave them there.
If you think these could be useful to other functions in the future, you can create a new namespace for them.

Partial::usage = "Partial[f_, args__] := partially applies arguments args to function f.";

PrintTestResults::usage = "PrintTestResults[testReport_] := Prints the results of a testReport in a terminal friendly manner";

SubstitutionRange::usage = "SubstitutionRange[template_Association] := Gives a range from 0 to the maximum possible substitution the template could have";

OldBaseTemplate::usage = "Gives the base template for a radius r k-ary rule.";
TakeNeighbourhoods::usage = "Returns the n first neighborhoods from a given space.";
TemplateFromNeighbourhoods::usage = "Builds a template given a list of neighbourhoods. Converts the neighbourhoods to symbols in the form xN, where N is the decimal conversion of the k-ary neighbourhood.";
Expand All @@ -23,33 +23,14 @@ KAryFromRuleTable::usage = "Auxiliary function that converts a rule table to its
RuleTableFromKAry::usage= "Auxiliary function that converts k-ary rule table to its classical representation.";
RuleTable::usage = "Creates the rule table of rnum, under Wolfram\.b4s lexicographic order. ";
RuleOutputFromNeighbourhood::usage="Yields the output bit of a given neighbourhood from rule rnum. The neighbourhood may be given as the k-ary sequence that defines it, or as the decimal number it represents (e.g, decimal 6 for neighbourhood {0, 1, 1, 0}, etc).";

ExceptionTemplates::usage= "ExceptionTemplates[t_List, k_Integer:2, r_Integer:2] generate all the templates with variable assignments that make the template t with k colors and r range invalid.";


PossibleStateReplacements::usage="Retorna todas as permuta\[CCedilla]\[OTilde]es poss\[IAcute]veis de estados de acordo com k.";


RawTemplate::usage="RawTemplate[t_List]: Receives a template t, and drops any special sintax construct from it. Currently, it removes expressions of the form x \[Element] {__}.";


ImprisonmentExpressions::usage="ImprisonmentExpressions[t_List]: Receives a template t, and returns all of the expressions of the form x \[Element] {__}.";


ValueRestrictions::usage = "ValueRestrictions[imprisonmentExpression_]: Returns an expression that represents the value restricions dictated by an ImprisonmentExpression. Example: ValueRestrictions[x1 \[Element] {0,1}] -> x1 == 0 || x1 == 1";


FreeVariableQ::usage = "FreeVariableQ[expression_]: Receives an expression, and returns true if the expression is a free variable and false otherwise.";


CorrespondsToNeighborhoodQ::usage = "CorrespondsToNeighborhoodQ[freeVariable_Symbol, nbIndex_Integer]: Receives a free variable expression and a neighborhood index, and returns true if the variable's index corresponds to the received nb index.";


PreservesIndexVariableDualityQ::usage = "PreservesIndexVariableDualityQ[template_]: Receives a template and returns true if the template preserver the index-variable diality.";


ConstantsToVariables::usage = "ConstantsToVariables[replacementRules_]: Receives a list of replacement rules, and converts any symbol of the type C[i_Integer] into its corresponding template variable, preserving the index-variable duality."

Begin["`Private`"];

SetAttributes[Partial, HoldAll];
Expand All @@ -62,7 +43,7 @@ OldBaseTemplate[k_Integer: 2, r_: 1] :=
RuleTemplateVars[ruletemplate_Association] :=
RuleTemplateVars[ruletemplate[["core"]]];
(*Deprecated!!*)
RuleTemplateVars[ruletemplate_] :=
RuleTemplateVars[ruletemplate_] :=
SortBy[Union[Cases[ruletemplate, _Symbol, Infinity]], FromDigits[StringDrop[SymbolName[#],1]]&]

TakeNeighbourhoods[n_Integer, k_Integer: 2, r_Integer: 1] :=
Expand Down Expand Up @@ -180,10 +161,36 @@ ImprisonmentExpressions[template_List]:= Cases[template, x_ \[Element] set_ ,Inf
ValueRestrictions[imprisonmentExpression_]:=
Apply[Or,imprisonmentExpression[[1]] == #&/@ imprisonmentExpression[[2]]];

RemoveContainedSubsSets[allSubSet_List, subSet_List] :=
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it seems this is not being used anywhere.

Module[{listToRemove, result},
listToRemove = ContainsAll[#, subSet] && subSet =!= # & /@ allSubSet;
result = MapThread[If[! #2, #1, ## &[]] &, {allSubSet, listToRemove}]
];

BooleanFromRule[x_ /; x[[2]] == 0] := Not[x[[1]]];
BooleanFromRule[x_ /; x[[2]] == 1] := x[[1]];

ConjunctionFromRuleSet[ruleSet_List] :=
Apply[And, Map[BooleanFromRule, ruleSet]];

DNFFromRuleSet[ruleSet_List] :=
Apply[Or, Map[ConjunctionFromRuleSet, ruleSet]];

MinimizedRuleSets[ruleSets_List] :=
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no tests for this function (add them if you think it is worth it)

RuleSetFromDNFF[BooleanMinimize[DNFFromRuleSet[ruleSets]]];

RuleSetFromDNFF[minimizeBooleanExpression_] := Module[{RootExpressionToSubSet, ExpressionToSubSet, LeafExpressionToSubSet},
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't need this Module here. You can simply declare the functions outside of RuleSetFromDNFF.

RootExpressionToSubSet[expr_ /; Head[expr] === Or] := Map[ExpressionToSubSet, expr, {1}] /. And -> List /. Or -> List;
RootExpressionToSubSet[expr_] := {ExpressionToSubSet[expr]} /. And -> List /. Or -> List;

ExpressionToSubSet[expr_ /; Head[expr] === And] := Map[LeafExpressionToSubSet, expr];
ExpressionToSubSet[expr_] := {LeafExpressionToSubSet[expr]};
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is ExpressionToSubset being used anywhere?


ExceptionTemplates[intemplate_, k_Integer:2, r_Integer:1] :=
MapThread[If[#2=== _,#1,#2]&,{OldBaseTemplate[k,r],#}]&/@Union[(If[NumberQ[#],#,_]&/@#)&/@((OldBaseTemplate[k,r]/.#[[1]])&/@Cases[{#[[2]],#[[1]]/.#[[2]]}&/@Flatten[Outer[List,{#[[1]]},#[[2]],1]&/@({#[[2]],MapThread[#1->#2&,{#[[1]],#[[2]]}]&/@#[[1]]}&/@({First@Outer[List,{#[[1]]},#[[2]],1],#[[3]]}&/@({#[[1]],Tuples[Range[0,k-1],Length[#[[1]]]],#[[2]]}&/@({RuleTemplateVars[{#}],#}&/@Select[intemplate,(Depth[#]>1)&])))),2],{_,x_/;\[Not]MemberQ[Range[0,k-1],x]}])]
LeafExpressionToSubSet[expr_ /; Head[expr] === Symbol] := expr -> 1;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is equivalent to

LeafExpressionToSubSet[expr_Symbol] := expr -> 1

Copy link
Owner

@mverardo mverardo Aug 16, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if ExpressionToSubSet is not being used, then LeafExpressionToSubSet is also not being used.

LeafExpressionToSubSet[expr_ /; Head[expr] === Not] := expr[[1]] -> 0;
Copy link
Owner

@mverardo mverardo Aug 16, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LeafExpressionToSubSet[expr_ /; Head[expr] === Not]
is equivalent to
LeafExpressionToSubSet[expr_Not]

if I'm not mistaken.


result = RootExpressionToSubSet[minimizeBooleanExpression]
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you don't need this result.

];

FreeVariableQ[expression_] := MatchQ[expression, _Symbol];

Expand All @@ -207,7 +214,7 @@ PrintTestResults[testReport_] :=
Module[{red = "\033[0;31m", green = "\033[0;32m", noColor = "\033[0m"},
Print[green <> "Suceeded: " <> ToString[testReport["TestsSucceededCount"]] <> noColor];
If[testReport["TestsFailedCount"] > 0,
Print[red <> "Failed: " <> ToString[testReport["TestsFailedCount"]] <> noColor]];
Print[red <> "Failed: " <> ToString[testReport["TestsFailedCount"]]<> "; Indices:" <> ToString[testReport["TestsFailedIndices"]] <> noColor]];
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🆒 😎

];

End[];
Expand Down
44 changes: 44 additions & 0 deletions TemplateOperations/Difference/Common.wl
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
(* ::Package:: *)

BeginPackage["CATemplates`TemplateOperations`Difference`Common`", {
"CATemplates`Basic`",
"CATemplates`CATemplate`"}];


DualEquationSystem::usage = "bl2";
DifferenceReplacementRules::usage = "
DifferenceReplacementRules[template1_List, template2_List]: Takes two templates template1 and template2, and returns the replacement rules that could be applied to template1 or template2 in order to find the diference between then. Returns {} if there is no possible diference template or if they are both templates are the same.
DifferenceReplacementRules[template1_List, template2_List, modulus_Integer]: Takes two templates template1 and template2, and returns the replacement rules that could be applied to template1 or template2 in order to find the diference between then. Returns {} if there is no possible diference template or if they are both templates are the same. Assumes both templates are modular.
";


Begin["`Private`"];

EquationSystem[template1_List,template2_List]:=
Equal @@ # & /@ Transpose[{template1, template2}];

DualEquationSystem[template1_List, template2_List] :=
Module[{notTemplate2, equationSystem, cleanEquationSystem, dualEquationSystem, dualEquationSystemResult},
equationSystem = EquationSystem[template1, template2];(*Make a equation System*)
cleanEquationSystem = Select[equationSystem, !TrueQ[#]&];(*Remove tautologies*)
dualEquationSystem = Map[Part[#, 1] == 1 - (Part[#, 2])&, cleanEquationSystem];(*Apply Not to all variables*)
dualEquationSystemResult = Or @@ (# & /@ dualEquationSystem) (*Change boolean operator AND to OR*)
];

DifferenceReplacementRules[template1_List, template2_List, modulus_Integer : 0] :=
Copy link
Owner

@mverardo mverardo Aug 16, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you receive full templates instead of their cores, you can check if you need to use a mudulus from their postExpansionFns instead of receiving it here. The current TemplateIntersection does this, and it simplifies things a little.

Module[{
templateVars = SortBy[Union[Flatten[{TemplateCoreVars[template1], TemplateCoreVars[template2]}, 1]],
FromDigits[StringDrop[SymbolName[#], 1]] &],
dualEquationSystem
},
dualEquationSystem = DualEquationSystem[template1, template2];
If[dualEquationSystem =!= False,
If[modulus === 0,
Union[Quiet[Solve[DualEquationSystem[template1, template2], templateVars]]],
Union[Quiet[Solve[DualEquationSystem[template1, template2], Reverse[templateVars], Modulus -> modulus]]]
], {}
]
];
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this {} supposed to be inside the If?
Also, fix indentation.


End[];
EndPackage[];
72 changes: 72 additions & 0 deletions TemplateOperations/Difference/ExceptionTemplates.wl
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
(* ::Package:: *)

BeginPackage[
"CATemplates`TemplateOperations`Difference`ExceptionTemplates`",
{
"CATemplates`Basic`",
"CATemplates`CATemplate`"
}
];

PossibleInvalidSubsets::usage = "bl1";
SubstitutionRangeVar::usage = "bl1";
ExpandVar::usage = "bl1";
ExpandVars::usage = "bl1";
InvalidSubSets::usage = "bl1";
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bogus usages

ExceptionTemplates::usage= "ExceptionTemplates[t_List, k_Integer:2, r_Real:1] generate all the templates with variable assignments that make the template t with k colors and r range invalid.";

Begin["`Private`"];
PossibleInvalidSubsets[intemplate_Association] := PossibleInvalidSubsets[intemplate[["rawList"]]];
PossibleInvalidSubsets[intemplate_List] := Select[intemplate, (Depth[#] > 1) &];

SubstitutionRangeVar[var_, k_Integer : 2] := Range[0, k^Length[TemplateCoreVars[{var}]] - 1];
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about renaming this to ExpansionRange, moving it to ExpandTemplate and using it there instead of doing it manually like we do today?


ExpandVar[var_, i_Integer] := Module[{variables = TemplateCoreVars[{var}], substitution, transformationRules, result},
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this related to template expasion? If not, please use another name so we don't get confused

substitution = Reverse[IntegerDigits[i, 2, Length[variables]]];
transformationRules = MapThread[#1 -> #2 &, {variables, substitution}];
result = var /. transformationRules;
If[result >= 2|| result < 0, transformationRules, (##) &[]]
];
ExpandVars[vars_, range_] :=
Module[{result}, result = Map[ExpandVar[vars, #] &, range];
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

prefer With instead of Module when you don't need mutable state (like here).

If[result == {}, Nothing, result]];

InvalidSubSets[intemplate_List] :=
Module[{possibleInvalids = PossibleInvalidSubsets[intemplate],
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this could be a With

result},
result =
MapThread[
ExpandVars, {possibleInvalids,
SubstitutionRangeVar[#, 2] & /@ possibleInvalids}];
If[result == {}, {}, Flatten[result, 1]]];

InvalidSubSets[intemplate_Association] := Module[{possibleInvalids = PossibleInvalidSubsets[intemplate]},
MapThread[ExpandVars, {possibleInvalids, SubstitutionRangeVar[#, intemplate[["k"]]]& /@ possibleInvalids}]
];
Copy link
Owner

@mverardo mverardo Aug 16, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

close ] in the previous line, and apply this rule to all the rest of the code.


ExceptionTemplates[intemplate_Association] :=
Module[{exceptionTemplates},
exceptionTemplates = ExceptionTemplates[intemplate[["core"]], intemplate[["k"]], intemplate[["r"]]];
BuildTemplate[intemplate[["k"]], intemplate[["r"]], #] & /@ exceptionTemplates
];

ExceptionTemplates[intemplate_List] :=
ExceptionTemplates[intemplate, 2, 1.0];

ExceptionTemplates[intemplate_List, k_ /; k === 2, r_Real : 1.0] :=
Module[{invalidSubsSets, filteredInvalidSubsSets, baseTemplate = OldBaseTemplate[k, r], result = {}},
invalidSubsSets = Union[
SortBy[InvalidSubSets[intemplate], Total]
];
If[invalidSubsSets =!= {},
filteredInvalidSubsSets = MinimizedRuleSets[invalidSubsSets];
result = (baseTemplate /. #) & /@ filteredInvalidSubsSets;
];
result
];

ExceptionTemplates[intemplate_List, k_Integer:2, r_Real : 1.0] :=
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is probably shadowing the previous definition of ExceptionTemplates. Please remove this and check if all tests keep passing.

MapThread[If[#2 === _, #1, #2]&, {OldBaseTemplate[k, r], #}]& /@ Union[(If[NumberQ[#], #, _]& /@ #)& /@ ((OldBaseTemplate[k, r] /. #[[1]])& /@ Cases[{#[[2]], #[[1]] /. #[[2]]}& /@ Flatten[Outer[List, {#[[1]]}, #[[2]], 1]& /@ ({#[[2]], MapThread[#1 -> #2&, {#[[1]], #[[2]]}]& /@ #[[1]]}& /@ ({First@Outer[List, {#[[1]]}, #[[2]], 1], #[[3]]}& /@ ({#[[1]], Tuples[Range[0, k - 1], Length[#[[1]]]], #[[2]]}& /@ ({TemplateCoreVars[{#}], #}& /@ Select[intemplate, (Depth[#] > 1)&])))), 2], {_, x_ /; \[Not]MemberQ[Range[0, k - 1], x]}])]

End[];
EndPackage[];
9 changes: 9 additions & 0 deletions TemplateOperations/Difference/Kernel/init.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
(* ::Package:: *)

Get["CATemplates`TemplateOperations`Difference`Common`"];

Get["CATemplates`TemplateOperations`Difference`RawDifference`"]

Get["CATemplates`TemplateOperations`Difference`TemplateDifference`"]

Get["CATemplates`TemplateOperations`Difference`ExceptionTemplates`"]
115 changes: 115 additions & 0 deletions TemplateOperations/Difference/RawDifference.wl
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
(* ::Package:: *)

BeginPackage[
"CATemplates`TemplateOperations`Difference`RawDifference`",
{
"CATemplates`Basic`",
"CATemplates`CATemplate`",
"CATemplates`TemplateOperations`Intersection`TemplateIntersection`",
"CATemplates`TemplateOperations`Difference`Common`",
"CATemplates`TemplateOperations`Difference`ExceptionTemplates`"}
];


RawDifference::usage = "bl1";
RawDifferenceOld::usage = "bl1";
RawDifferenceDirect::usage = "bl1";
RawDifferenceDirectOld::usage = "bl1";
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bogus usages


Begin["`Private`"];

RawDifferenceOld[template1_List, template2_List, radius_ : 1.0] :=
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is not being used

Module[{templateIntersection, exceptionTemplates, templateDifferenceP1, templateDifferenceP2, templateDifference, replacementRules, replacementRulesFinal},
templateIntersection = Flatten[RawIntersection[template1, template2]];
If[!ValidTemplateCoreQ[templateIntersection] || templateIntersection === {},
templateDifference = {template1};,
replacementRules = DifferenceReplacementRules[template1, templateIntersection];
replacementRulesFinal = Select[replacementRules, FreeQ[#, _Rational] &];

If[replacementRulesFinal == {}, templateDifference = {};,
templateDifferenceP1 = template1 /. replacementRulesFinal;
exceptionTemplates = ExceptionTemplates[templateIntersection, 2, radius];
templateDifferenceP2 = RawIntersection[template1, #] & /@ exceptionTemplates;
templateDifference = Join[templateDifferenceP1, templateDifferenceP2];
]
];
templateDifference
];

RawDifferenceDirectOld[template1_List, template2_List, radius_ : 1.0] :=
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here

Module[{templateIntersection, exceptionTemplates, templateDifferenceP1, templateDifferenceP2, templateDifference, replacementRules, replacementRulesFinal},
templateIntersection = Flatten[RawIntersection[template1, template2]];
If[!ValidTemplateCoreQ[templateIntersection] || templateIntersection === {},
templateDifference = {template1};,
replacementRules = DifferenceReplacementRules[template1, template2];
replacementRulesFinal = Select[replacementRules, FreeQ[#, _Rational] &];
replacementRulesFinal = Select[replacementRules, ContainsOnly[TemplateCoreVars[#], TemplateCoreVars[template1]]&];

If[replacementRulesFinal == {},
templateDifferenceP1 = {};,
templateDifferenceP1 = template1 /. replacementRulesFinal;
];
exceptionTemplates = ExceptionTemplates[template2, 2, radius];
templateDifferenceP2 = RawIntersection[template1, #] & /@ exceptionTemplates;
templateDifference = Join[templateDifferenceP1, templateDifferenceP2];
(*Print[templateDifferenceP1];*)
(*Print[templateDifferenceP2];*)
];
templateDifference
];

RawDifference[template1A_Association, template2A_Association, radius_ : 1.0] :=
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you try to extract some of this code to functions with meaningful names?
Also, avoid the Module

Module[{template1, template2, templateIntersection, template1And2HasIntersection, templateIntersectionA, exceptionTemplates, templateDifferenceP1, templateDifferenceP2, templateDifference, replacementRules, replacementRulesFinal},
template1 = template1A[["core"]];
template2 = template2A[["core"]];
templateIntersectionA = TemplateIntersection[template1A,template2A];
templateIntersection = templateIntersectionA[["core"]];
template1And2HasIntersection = !(!ValidTemplateCoreQ[templateIntersection] || templateIntersection === {});
If[!template1And2HasIntersection,
templateDifference = {template1};,
replacementRules = DifferenceReplacementRules[template1, templateIntersection];
replacementRulesFinal = Select[replacementRules, FreeQ[#, _Rational] &];
replacementRulesFinal = Select[replacementRules, ContainsOnly[TemplateCoreVars[#], TemplateCoreVars[template1]]&];

If[replacementRulesFinal == {},
templateDifferenceP1 = {};,
templateDifferenceP1 = template1 /. replacementRulesFinal;
];
exceptionTemplates = ExceptionTemplates[templateIntersectionA];
templateDifferenceP2 = TemplateIntersection[template1A, #] & /@ exceptionTemplates;
templateDifferenceP2 = #[["core"]] & /@templateDifferenceP2;
templateDifference = Join[templateDifferenceP1, templateDifferenceP2];
];
templateDifference
];


RawDifferenceDirect[template1A_Association, template2A_Association, radius_ : 1.0] :=
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the difference between RawDifference and RawDifferenceDirect?

Module[{template1, template2, templateIntersection, template1And2HasIntersection, templateIntersectionA, exceptionTemplates, templateDifferenceP1, templateDifferenceP2, templateDifference, replacementRules, replacementRulesFinal},
template1 = template1A[["core"]];
template2 = template2A[["core"]];
templateIntersectionA = TemplateIntersection[template1A,template2A];
templateIntersection = templateIntersectionA[["core"]];
template1And2HasIntersection = !(!ValidTemplateCoreQ[templateIntersection] || templateIntersection === {});
If[!template1And2HasIntersection,
templateDifference = {template1};,
replacementRules = DifferenceReplacementRules[template1, template2];
replacementRulesFinal = Select[replacementRules, FreeQ[#, _Rational] &];
replacementRulesFinal = Select[replacementRules, ContainsOnly[TemplateCoreVars[#], TemplateCoreVars[template1]]&];

If[replacementRulesFinal == {},
templateDifferenceP1 = {};,
templateDifferenceP1 = template1 /. replacementRulesFinal;
];
exceptionTemplates = ExceptionTemplates[template2A];
templateDifferenceP2 = TemplateIntersection[template1A, #] & /@ exceptionTemplates;
templateDifferenceP2 = #[["core"]] & /@templateDifferenceP2;
templateDifference = Join[templateDifferenceP1, templateDifferenceP2];
];
templateDifference
];



End[];
EndPackage[];
Loading