Imported Upstream version ceres 1.13.0
[platform/upstream/ceres-solver.git] / internal / ceres / generate_template_specializations.py
1 # Ceres Solver - A fast non-linear least squares minimizer
2 # Copyright 2015 Google Inc. All rights reserved.
3 # http://ceres-solver.org/
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions are met:
7 #
8 # * Redistributions of source code must retain the above copyright notice,
9 #   this list of conditions and the following disclaimer.
10 # * Redistributions in binary form must reproduce the above copyright notice,
11 #   this list of conditions and the following disclaimer in the documentation
12 #   and/or other materials provided with the distribution.
13 # * Neither the name of Google Inc. nor the names of its contributors may be
14 #   used to endorse or promote products derived from this software without
15 #   specific prior written permission.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 # POSSIBILITY OF SUCH DAMAGE.
28 #
29 # Author: sameeragarwal@google.com (Sameer Agarwal)
30 #
31 # Script for explicitly generating template specialization of the
32 # SchurEliminator class. It is a rather large class
33 # and the number of explicit instantiations is also large. Explicitly
34 # generating these instantiations in separate .cc files breaks the
35 # compilation into separate compilation unit rather than one large cc
36 # file which takes 2+GB of RAM to compile.
37 #
38 # This script creates three sets of files.
39 #
40 # 1. schur_eliminator_x_x_x.cc and partitioned_matrix_view_x_x_x.cc
41 # where, the x indicates the template parameters and
42 #
43 # 2. schur_eliminator.cc & partitioned_matrix_view.cc
44 #
45 # that contains a factory function for instantiating these classes
46 # based on runtime parameters.
47 #
48 # 3. schur_templates.cc
49 #
50 # that contains a function which can be queried to determine what
51 # template specializations are available.
52 #
53 # The following list of tuples, specializations indicates the set of
54 # specializations that is generated.
55 SPECIALIZATIONS = [(2, 2, 2),
56                    (2, 2, 3),
57                    (2, 2, 4),
58                    (2, 2, "Eigen::Dynamic"),
59                    (2, 3, 3),
60                    (2, 3, 4),
61                    (2, 3, 6),
62                    (2, 3, 9),
63                    (2, 3, "Eigen::Dynamic"),
64                    (2, 4, 3),
65                    (2, 4, 4),
66                    (2, 4, 8),
67                    (2, 4, 9),
68                    (2, 4, "Eigen::Dynamic"),
69                    (2, "Eigen::Dynamic", "Eigen::Dynamic"),
70                    (4, 4, 2),
71                    (4, 4, 3),
72                    (4, 4, 4),
73                    (4, 4, "Eigen::Dynamic")]
74
75 import schur_eliminator_template
76 import partitioned_matrix_view_template
77 import os
78 import glob
79
80 def SuffixForSize(size):
81   if size == "Eigen::Dynamic":
82     return "d"
83   return str(size)
84
85 def SpecializationFilename(prefix, row_block_size, e_block_size, f_block_size):
86   return "_".join([prefix] + map(SuffixForSize, (row_block_size,
87                                                  e_block_size,
88                                                  f_block_size)))
89
90 def GenerateFactoryConditional(row_block_size, e_block_size, f_block_size):
91   conditionals = []
92   if (row_block_size != "Eigen::Dynamic"):
93     conditionals.append("(options.row_block_size == %s)" % row_block_size)
94   if (e_block_size != "Eigen::Dynamic"):
95     conditionals.append("(options.e_block_size == %s)" % e_block_size)
96   if (f_block_size != "Eigen::Dynamic"):
97     conditionals.append("(options.f_block_size == %s)" % f_block_size)
98   if (len(conditionals) == 0):
99     return "%s"
100
101   if (len(conditionals) == 1):
102     return " if " + conditionals[0] + "{\n  %s\n }\n"
103
104   return " if (" + " &&\n     ".join(conditionals) + ") {\n  %s\n }\n"
105
106 def Specialize(name, data):
107   """
108   Generate specialization code and the conditionals to instantiate it.
109   """
110
111   # Specialization files
112   for row_block_size, e_block_size, f_block_size in SPECIALIZATIONS:
113       output = SpecializationFilename("generated/" + name,
114                                       row_block_size,
115                                       e_block_size,
116                                       f_block_size) + ".cc"
117
118       with open(output, "w") as f:
119         f.write(data["HEADER"])
120         f.write(data["SPECIALIZATION_FILE"] %
121                   (row_block_size, e_block_size, f_block_size))
122
123   # Generate the _d_d_d specialization.
124   output = SpecializationFilename("generated/" + name,
125                                    "Eigen::Dynamic",
126                                    "Eigen::Dynamic",
127                                    "Eigen::Dynamic") + ".cc"
128   with open(output, "w") as f:
129     f.write(data["HEADER"])
130     f.write(data["DYNAMIC_FILE"] %
131               ("Eigen::Dynamic", "Eigen::Dynamic", "Eigen::Dynamic"))
132
133   # Factory
134   with open(name + ".cc", "w") as f:
135     f.write(data["HEADER"])
136     f.write(data["FACTORY_FILE_HEADER"])
137     for row_block_size, e_block_size, f_block_size in SPECIALIZATIONS:
138         factory_conditional = GenerateFactoryConditional(
139             row_block_size, e_block_size, f_block_size)
140         factory = data["FACTORY"] % (row_block_size, e_block_size, f_block_size)
141         f.write(factory_conditional % factory);
142     f.write(data["FACTORY_FOOTER"])
143
144 QUERY_HEADER = """// Ceres Solver - A fast non-linear least squares minimizer
145 // Copyright 2017 Google Inc. All rights reserved.
146 // http://ceres-solver.org/
147 //
148 // Redistribution and use in source and binary forms, with or without
149 // modification, are permitted provided that the following conditions are met:
150 //
151 // * Redistributions of source code must retain the above copyright notice,
152 //   this list of conditions and the following disclaimer.
153 // * Redistributions in binary form must reproduce the above copyright notice,
154 //   this list of conditions and the following disclaimer in the documentation
155 //   and/or other materials provided with the distribution.
156 // * Neither the name of Google Inc. nor the names of its contributors may be
157 //   used to endorse or promote products derived from this software without
158 //   specific prior written permission.
159 //
160 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
161 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
162 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
163 // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
164 // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
165 // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
166 // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
167 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
168 // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
169 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
170 // POSSIBILITY OF SUCH DAMAGE.
171 //
172 // Author: sameeragarwal@google.com (Sameer Agarwal)
173 //
174 // What template specializations are available.
175 //
176 // ========================================
177 // THIS FILE IS AUTOGENERATED. DO NOT EDIT.
178 // THIS FILE IS AUTOGENERATED. DO NOT EDIT.
179 // THIS FILE IS AUTOGENERATED. DO NOT EDIT.
180 // THIS FILE IS AUTOGENERATED. DO NOT EDIT.
181 //=========================================
182 //
183 // This file is generated using generate_template_specializations.py.
184 """
185
186 QUERY_FILE_HEADER = """
187 #include "ceres/internal/eigen.h"
188 #include "ceres/schur_templates.h"
189
190 namespace ceres {
191 namespace internal {
192
193 void GetBestSchurTemplateSpecialization(int* row_block_size,
194                                         int* e_block_size,
195                                         int* f_block_size) {
196   LinearSolver::Options options;
197   options.row_block_size = *row_block_size;
198   options.e_block_size = *e_block_size;
199   options.f_block_size = *f_block_size;
200   *row_block_size = Eigen::Dynamic;
201   *e_block_size = Eigen::Dynamic;
202   *f_block_size = Eigen::Dynamic;
203 #ifndef CERES_RESTRICT_SCHUR_SPECIALIZATION
204 """
205
206 QUERY_FOOTER = """
207 #endif
208   return;
209 }
210
211 }  // namespace internal
212 }  // namespace ceres
213 """
214
215 QUERY_ACTION = """ *row_block_size = %s;
216    *e_block_size = %s;
217    *f_block_size = %s;
218   return;"""
219
220 def GenerateQueryFile():
221   """
222   Generate file that allows querying for available template specializations.
223   """
224
225   with open("schur_templates.cc", "w") as f:
226     f.write(QUERY_HEADER)
227     f.write(QUERY_FILE_HEADER)
228     for row_block_size, e_block_size, f_block_size in SPECIALIZATIONS:
229       factory_conditional = GenerateFactoryConditional(
230         row_block_size, e_block_size, f_block_size)
231       action = QUERY_ACTION % (row_block_size, e_block_size, f_block_size)
232       f.write(factory_conditional % action)
233     f.write(QUERY_FOOTER)
234
235
236 if __name__ == "__main__":
237   for f in glob.glob("generated/*"):
238     os.remove(f)
239
240   Specialize("schur_eliminator",
241                schur_eliminator_template.__dict__)
242   Specialize("partitioned_matrix_view",
243                partitioned_matrix_view_template.__dict__)
244   GenerateQueryFile()