-
Notifications
You must be signed in to change notification settings - Fork 1
/
coordinate_system_implementation_generator.py
1901 lines (1660 loc) · 99.3 KB
/
coordinate_system_implementation_generator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
import os
import sys
import random
import numpy as np
import sympy as sym
from collections import OrderedDict
from metric import Metric
from christoffelSymbols import ChristoffelSymbol2ndKind
from riemannTensor import RiemannTensor
from ricciTensor import RicciTensor
from ricciScalar import RicciScalar
class JavaCoordinateSystemCreator(object):
"""
Class for creating an implementation of the eu.hoefel.coordinates.CoordinateSystem Java interface via sympy.
Parameters
----------
java_class_name : str
The class name to be used for the Java class.
metric : Metric
The metric of the coordinate system.
axes : dict
The dictionary containing the dimension as key and the corresponding unit as a string. Note that
the key of the default dimension should be -1 and specific implementations like 'SiBaseUnit.METER'
are also allowed.
java_name : str, optional
The name of the coordinate system. By default, if the java_class_name ends in 'Coordinates', it will
use the preceding characters.
extra_parameters : dict, optional
Additional parameters required for the coordinate system. Their name should be supplied as key
and their type as value.
Returns
-------
JavaCoordinateSystemCreator
the class allowing to create a Java implementation of the specified coordinate system
"""
def __init__(self, java_class_name: str, metric: Metric, axes: dict, java_name=None, extra_parameters=None):
self.java_class_name = str(java_class_name)
self.g = metric
self.dim = self.g.dim()
self.symbols = self.g.symbols
if self.g.to_base_point is not None:
self.to_base_point = self.g.to_base_point
self.from_base_point = None
self.base_symbols = None
else:
self.to_base_point = None
self.from_base_point = None
self.base_symbols = None
self.gamma = ChristoffelSymbol2ndKind(self.g, self.g.symbols)
self.riem = RiemannTensor(self.g, self.gamma, self.g.symbols)
self.ric = RicciTensor(self.riem)
self.ric_scalar = RicciScalar(self.ric,self.g)
self.code = ""
if java_name == '' or java_name is None:
index = java_class_name.index('Coordinates')
if index == -1:
raise Exception("Cannot guess java_name, please supply explicitly")
self.java_name = java_class_name[:index]
else:
self.java_name = java_name
if axes is None:
raise Exception("Cannot create default axes!")
else:
self.axes = axes
self.coordinate_system_symbols = []
# needs to be a dictionary with type info
self.extra_parameters = extra_parameters
self.extra_imports = []
self.__extra_symbol_check = {}
self.unable_to_invert = False
self.inv_transformation = None
self.variable_lower_limit = {}
self.variable_upper_limit = {}
self.__use_validate_position = False
def save_to(self, save_folder: str, package='eu.hoefel.coordinates'):
"""
Saves the generated Java implementation to the specified folder.
Parameters
----------
save_folder : str
The path to save to, except that the package gets appended.
package : str, optional
The package to use. Defaults to 'eu.hoefel.coordinates'.
"""
print("Trying to simplify input.")
if self.to_base_point is not None:
for i in range(len(self.to_base_point)):
self.to_base_point[i] = self.to_base_point[i].simplify()
if self.from_base_point is not None:
for i in range(len(self.from_base_point)):
self.from_base_point[i] = self.from_base_point[i].simplify()
print("Creating implementation. This may take a while, please be patient.")
print("Please note in the meantime that the resulting file may contain TODOs.")
print("Most, but potentially not all of them will be related to documentation.")
print("Please address the TODOs.")
# run once to collect all things to be imported
self.__build(True)
# throw away the generated code, but not the collected extra imports
self.code = ""
# throw away duplicate imports
self.extra_imports = list(dict.fromkeys(self.extra_imports))
# Rebuild with the extra imports in place
self.__build(False)
if not save_folder.endswith("/"): save_folder += "/"
save_folder += package.replace(".", "/")
if not save_folder.endswith("/"): save_folder += "/"
print("Saving to " + save_folder)
if not os.path.exists(save_folder):
os.makedirs(save_folder)
filename = self.java_class_name + ".java"
self.code = "package " + package + ";\n\n" + self.code
with open(save_folder + filename, "w+") as file:
file.write(self.code)
def __build(self, mute):
"""
Builds the code for a Java class implementing the eu.hoefel.coordinates.CoordinateSystem interface.
Parameters
----------
mute : bool
Print (most) stuff only if False
"""
self.code = ""
if not mute: print("Build header...")
self.__build_header()
if not mute: print("Build Constructor...")
self.__build_constructor()
if not mute: print("Build update position...")
self.__build_update_position()
if not mute: print("Build dimension...")
self.__build_dimension()
if not mute: print("Build isOrthogonal...")
self.__build_isOrthogonal()
if not mute: print("Build toBaseUnits...")
self.__build_to_base_transformation_units()
if not mute: print("Build toBasePoint...")
self.__build_to_base_transformation_point()
if not mute: print("Build fromBasePoint...")
self.__build_from_base_transformation_point()
if not mute: print("Build toBaseVector...")
self.__build_to_base_transformation_vector()
if not mute: print("Build fromBaseVector...")
self.__build_from_base_transformation_vector()
if not mute: print("Build metric coefficient...")
self.__build_metric_coefficient()
if not mute: print("Build metric tensor...")
self.__build_metric_tensor()
if not mute: print("Build Jacobian...")
self.__build_jacobian_determinant()
if not mute: print("Build Christoffel Symbol 1st kind...")
self.__build_christoffel_symbols_1st_kind()
if not mute: print("Build Christoffel Symbol 2nd kind...")
self.__build_christoffel_symbols_2nd_kind()
if not mute: print("Build Riemann tensor...")
self.__build_riemann_tensor(mute=mute)
if not mute: print("Build isFlat...")
self.__build_isFlat()
if not mute: print("Build Ricci tensor...")
self.__build_ricci_tensor()
if not mute: print("Build Ricci scalar...")
self.__build_ricci_scalar()
self.code += "}\n"
def __is_java_import(self, string: str) -> bool:
"""
Checks whether the specified string is a java import.
Parameters
----------
string : str
The string to check.
Returns
-------
Boolean
true if the string is for a Java import
"""
return string.startswith("import java.")
def __is_eu_hoefel_import(self, string: str) -> bool:
"""
Checks whether the specified string is a eu.hoefel.* import.
Parameters
----------
string : str
The string to check.
Returns
-------
Boolean
true if the string is for a eu.hoefel.* import
"""
return string.startswith("import eu.hoefel.")
def __build_header(self):
"""
Builds the header of the Java implementation of the eu.hoefel.coordinates.CoordinateSystem interface
and attaches it to the variable representing the Java code.
"""
found = False
for extra_import in self.extra_imports:
if self.__is_java_import(extra_import):
self.code += extra_import + "\n"
found = True
if found: self.code += "\n"
found = False
for extra_import in self.extra_imports:
if self.__is_eu_hoefel_import(extra_import):
self.code += extra_import + "\n"
found = True
if found: self.code += "\n"
found = False
for extra_import in self.extra_imports:
if not self.__is_java_import(extra_import) and not self.__is_eu_hoefel_import(extra_import):
self.code += extra_import + "\n"
found = True
if found: self.code += "\n"
self.extra_imports.append("import java.util.NavigableSet;")
if self.extra_parameters is not None:
self.extra_imports.append("import java.util.Objects;")
else:
self.extra_imports.append("import java.util.function.Consumer;")
self.extra_imports.append("import eu.hoefel.coordinates.axes.Axes;")
self.extra_imports.append("import eu.hoefel.coordinates.axes.Axis;")
self.extra_imports.append("import eu.hoefel.coordinates.CoordinateSystemSymbols;")
self.code += "/**\n"
self.code += " * TODO\n"
self.code += " * \n"
self.code += " * @param axes the axes defining the coordinate system, not null\n"
if self.extra_parameters is not None:
for name, _ in self.extra_parameters.items():
self.code += " * @param " + name + " TODO\n"
self.code += " */\n"
if self.coordinate_system_symbols != []:
self.code += "@CoordinateSystemSymbols({\"" + "\", \"".join(self.coordinate_system_symbols) + "\"})\n"
else:
self.code += "@CoordinateSystemSymbols({\"\"}) // TODO: add symbols representing the coordinate system, e.g. 'cartesian' and 'cart' for the cartesian coordinate system\n"
self.code += "public final record " + self.java_class_name + "(NavigableSet<Axis> axes"
if self.extra_parameters is not None:
for name, param_type in self.extra_parameters.items():
self.code += ", " + param_type + " " + name
self.code += ") implements CoordinateSystem {\n\n"
self.code += " /** The default axes. */\n"
self.code += " public static final NavigableSet<Axis> DEFAULT_AXES = Axes.of(\n"
counter = 0
for dimension, unit in sorted(self.axes.items()):
axis = ""
if dimension == -1: # default axis
axis += "new Axis("
else:
axis += "new Axis(" + str(dimension) + ", "
if "." in unit: # probably smth like SiBaseUnit.METER
axis += unit
# handle some standard units specially
if unit.startswith("SiBaseUnit"): self.extra_imports.append("import eu.hoefel.unit.si.SiBaseUnit;")
if unit.startswith("SiDerivedUnit"): self.extra_imports.append("import eu.hoefel.unit.si.SiDerivedUnit;")
if unit.startswith("SiCommonUnit"): self.extra_imports.append("import eu.hoefel.unit.si.SiCommonUnit;")
else:
axis += "Unit.of(\"" + unit + "\")"
axis += ")"
self.code += " " + axis
counter += 1
if counter < len(self.axes): self.code += ",\n"
self.code += ");\n\n"
if self.extra_parameters is None:
self.code += " /**\n"
self.code += " * The consumer useful for checking the arguments in\n"
self.code += " * {@link #" + self.java_class_name + "(Object...)}.\n"
self.code += " */\n"
self.code += " private static final Consumer<Object[]> ARG_CHECK = args -> Axes.DEFAULT_ARG_CHECK.accept(\"" + self.java_name + "\", args);\n\n"
def __build_constructor(self):
"""
Attaches the Java code for constructors to the code.
"""
self.code += " /** Constructs a new " + self.java_name.lower() + " coordinate system. */\n"
self.code += " public " + self.java_class_name + " {\n"
self.extra_imports.append("import java.util.Objects;")
self.code += " Objects.requireNonNull(axes, \"Axes may not be null. \"\n"
self.code += " + \"Use the DEFAULT_AXES"
if self.extra_parameters is not None:
self.code += " or the constructor that just requires " + str([*self.extra_parameters.keys()]) + " to get a reasonable default."
else:
self.code += " or the empty constructor to get a reasonable default."
self.code += "\");\n"
for dimension in sorted(self.__extra_symbol_check.keys()):
self.code += "\n"
self.code += self.__extra_symbol_check[dimension]
if self.extra_parameters is not None:
for extra_symbol in sorted(self.extra_parameters.keys()):
expression_in_equation = extra_symbol
is_constant = self.extra_parameters[extra_symbol] == 'Constant'
if is_constant: expression_in_equation+= ".value()"
if extra_symbol in self.variable_lower_limit and extra_symbol in self.variable_upper_limit:
self.code += "\n"
self.code += " if (" + expression_in_equation + " < " + str(self.variable_lower_limit[extra_symbol]) + " || " + expression_in_equation + " > " + str(self.variable_upper_limit[extra_symbol]) + ") {\n"
self.code += " throw new IllegalArgumentException(\"'" + extra_symbol + "' needs to be between " + str(self.variable_lower_limit[extra_symbol]) + " and " + str(self.variable_upper_limit[extra_symbol]) + ", but is \" + " + extra_symbol + ");\n"
self.code += " }\n"
elif extra_symbol in self.variable_lower_limit:
self.code += "\n"
self.code += " if (" + expression_in_equation + " < " + str(self.variable_lower_limit[extra_symbol]) + ") {\n"
self.code += " throw new IllegalArgumentException(\"'" + extra_symbol + "' needs to be above " + str(self.variable_lower_limit[extra_symbol]) + ", but is \" + " + extra_symbol + ");\n"
self.code += " }\n"
elif extra_symbol in self.variable_upper_limit:
self.code += "\n"
self.code += " if (" + expression_in_equation + " > " + str(self.variable_upper_limit[extra_symbol]) + ") {\n"
self.code += " throw new IllegalArgumentException(\"'" + extra_symbol + "' needs to be below " + str(self.variable_upper_limit[extra_symbol]) + ", but is \" + " + extra_symbol + ");\n"
self.code += " }\n"
self.code += " }\n\n"
self.code += " /**\n"
self.code += " * Constructs a new " + self.java_name.lower() + " coordinate system.\n"
self.code += " * \n"
self.code += " * @param args the arguments, must be either {@link Axes} or {@link Axis}, which\n"
self.code += " * will take precedence over the {@link #DEFAULT_AXES} if given. If\n"
self.code += " * no arguments are given, the default axes will be used.\n"
if self.extra_parameters is not None:
self.code += " * Further required arguments may also be passed in here, but (if \n"
self.code += " * they are doubles or {@link Constant}) they have to be in the \n"
self.code += " * same order in which they are specified in the record declaration.\n"
self.code += " */\n"
if self.extra_parameters is None:
self.code += " public " + self.java_class_name + "(Object... args) {\n"
self.code += " this(Axes.fromArgs(DEFAULT_AXES, ARG_CHECK, args));\n"
self.code += " }\n\n"
else:
self.code += " public " + self.java_class_name + "(Object... args) {\n"
add_warning = 'double' in self.extra_parameters.values() and 'Constant' in self.extra_parameters.values()
if add_warning:
self.code += " // Note that using both doubleFromArgs and constantFromArgs is not save if the\n"
self.code += " // values are input as strings that only contain a number and not an additional\n"
self.code += " // unit (for the constants)\n"
self.code += " this(Axes.fromArgs(DEFAULT_AXES, args)"
doubleIndex = 0
constantIndex = 0
for name, param_type in self.extra_parameters.items():
if param_type == "double":
self.extra_imports.append("import eu.hoefel.coordinates.CoordinateSystems;")
self.code += ", CoordinateSystems.doubleFromArgs(" + str(doubleIndex) + ", args)"
doubleIndex += 1
elif param_type == 'Constant':
self.extra_imports.append("import eu.hoefel.unit.constant.Constant;")
self.code += ", CoordinateSystems.constantFromArgs(" + str(constantIndex) + ", args)"
constantIndex += 1
else:
raise Exception("Don't know how to handle " + param_type + " for variable '" + name + "'!")
self.code += ");\n"
self.code += " }\n\n"
self.code += " /**\n"
self.code += " * Constructs a new " + self.java_name.lower() + " coordinate system.\n"
self.code += " * \n"
if self.extra_parameters is not None:
for name, _ in self.extra_parameters.items():
self.code += " * @param " + name + " TODO\n"
self.code += " */\n"
self.code += " public " + self.java_class_name + "("
parms = ""
for name, param_type in self.extra_parameters.items():
parms += ", " + param_type + " " + name
self.code += parms[2:]
self.code += ") {\n"
self.code += " this(DEFAULT_AXES, "
parms = ""
for name, param_type in self.extra_parameters.items():
parms += ", " + name
self.code += parms[2:]
self.code += ");\n"
self.code += " }\n\n"
def __build_update_position(self):
"""
Attaches the code to validate the position (in the current coordinate system), if limits are given.
"""
symbols_str = [str(symbol) for symbol in self.symbols]
self.__use_validate_position = True # we probably can always use it
if self.__use_validate_position:
self.code += " /**\n"
self.code += " * Validates the position, i.e. it throws an exception if a dimension of the \n"
self.code += " * position is out of range.\n"
self.code += " * \n"
self.code += " * @param position the position to validate\n"
self.code += " * @throw IllegalArgumentException if the assumptions about the dimensionality \n"
self.code += " * or the valid range of any dimension of the input are violated.\n"
self.code += " */\n"
self.code += " private void validatePosition(double[] position) {\n"
self.code += " Objects.requireNonNull(position);\n"
self.code += "\n"
self.code += " if (position.length > dimension()) {\n"
self.code += " throw new IllegalArgumentException(\n"
self.code += " \"The given dimensionality exceeds the maximum supported dimensionality (%d vs %d)\"\n"
self.code += " .formatted(position.length, dimension()));\n"
self.code += " }\n"
for symbol in symbols_str:
index = symbols_str.index(symbol)
if symbol in self.variable_lower_limit and symbol in self.variable_upper_limit:
self.code += "\n"
self.code += " if (position[" + str(index) + "] < " + str(self.variable_lower_limit[symbol]) + " || position[" + str(index) + "] > " + str(self.variable_upper_limit[symbol]) + ") {\n"
self.code += " throw new IllegalArgumentException(\"position[" + str(index) + "] needs to be between " + str(self.variable_lower_limit[symbol]) + " and " + str(self.variable_upper_limit[symbol]) + ", but is \" + position[" + str(index) + "]);\n"
self.code += " }\n"
elif symbol in self.variable_lower_limit:
self.code += "\n"
self.code += " if (position[" + str(index) + "] < " + str(self.variable_lower_limit[symbol]) + ") {\n"
self.code += " throw new IllegalArgumentException(\"position[" + str(index) + "] needs to be above " + str(self.variable_lower_limit[symbol]) + ", but is \" + position[" + str(index) + "]);\n"
self.code += " }\n"
elif symbol in self.variable_upper_limit:
self.code += "\n"
self.code += " if (position[" + str(index) + "] > " + str(self.variable_upper_limit[symbol]) + ") {\n"
self.code += " throw new IllegalArgumentException(\"position[" + str(index) + "] needs to be below " + str(self.variable_upper_limit[symbol]) + ", but is \" + position[" + str(index) + "]);\n"
self.code += " }\n"
self.code += " }\n\n"
@staticmethod
def __simplify(expr):
# first simplify, if the expression is not too long
if len(str(expr)) > 75: return expr
# first simplify
expr = expr.simplify()
# then expand trigonometric funcs
expr = sym.expand_trig(expr)
# then simplify again
expr = expr.simplify()
# then try to rewrite it in terms of exp funcs
expr_exp = expr.rewrite(sym.exp)
# simplify again
expr_exp = expr_exp.simplify()
if len(str(expr_exp)) < len(str(expr)) and not 'I' in str(expr_exp):
return expr_exp
return expr
def __build_to_base_transformation_units(self):
"""
Attaches the Java code for a method that provides the corresponding units in the corresponding base coordinate system.
"""
self.extra_imports.append("import java.util.NavigableMap;")
self.extra_imports.append("import eu.hoefel.unit.Unit;")
self.extra_imports.append("import eu.hoefel.unit.Units;")
self.code += " @Override\n"
self.code += " public NavigableMap<Integer, Unit> toBaseUnits() {\n"
self.code += " NavigableMap<Integer, Unit> map = new TreeMap<>();\n"
self.extra_imports.append("import java.util.TreeMap;")
#try:
for dim, transformation in enumerate(self.to_base_point):
# potentially add check for radian equality of some units
self.__check_for_func_args(transformation)
# remove specific funcs that do not change the unit
expr = self.__remove_specific_funcs(transformation)
# remove funcs (but leave their arguments in place) that do not change the unit
expr = self.__remove_irrelevant_funcs(expr)
# now we should have a 'clean' equation, i.e. only +* and ** should be left
# get rid of + and keep only one term as summands don't change the unit
expr = self.__keep_one_summand(expr).simplify()
self.dimension_exponents = {}
# so we have only * and ** left
self.__collect_exponents(expr, self.symbols)
base_unit = ""
for counter, parm in enumerate(self.dimension_exponents.keys()):
if not self.dimension_exponents[parm].is_integer:
raise Exception("Can only handle integer exponents at the moment.")
if counter > 0:
base_unit += " + "
if type(parm) is str:
# this an extra param of type Constant
base_unit += str(parm) + ".unit().symbols().get(0)"
else:
base_unit += "axis(" + str(parm) + ").unit().symbols().get(0)"
separator = " " if counter < len(self.dimension_exponents) - 1 else ""
if self.dimension_exponents[parm] != 1:
base_unit += " + \"^" + str(int(self.dimension_exponents[parm])) + separator + "\""
elif separator != "":
base_unit += " + \" \""
if len(self.dimension_exponents) == 1 and not "^" in base_unit:
if type(parm) is str:
self.code += " map.put(" + str(dim) + ", " + str(parm) + ".unit());\n"
else:
self.code += " map.put(" + str(dim) + ", axis(" + str(parm) + ").unit());\n"
else:
if base_unit == "": base_unit = "\"\""
self.code += " map.put(" + str(dim) + ", Unit.of(Units.simplify(" + base_unit + ")));\n"
self.code += " return Collections.unmodifiableNavigableMap(map);\n"
self.extra_imports.append("import java.util.Collections;")
#except Exception as e:
# print("error: " + str(e))
# self.code += " // TODO: Implement\n"
# self.code += " throw new UnsupportedOperationException(\"Failed to automatically derive the corresponding base units!\")"
self.code += " }\n"
self.code += "\n"
def __check_for_func_args(self, expr):
"""
Checks for specific functions that do not change the units of the expression,
which potentially allows to add a check in the constructor.
Parameters
----------
expr : sympy expression
The sympy expression to remove specific functions in
"""
trafo = str(expr)
# try to recognize trigonometric functions
# we know that the arguments of them need to be dimensionless, i.e. convertible to radians
funcs = []
# add math symbols
funcs.append('asin')
funcs.append('acos')
funcs.append('atan')
funcs.append('atan2')
funcs.append('acot')
funcs.append('asinh')
funcs.append('acosh')
funcs.append('sinh')
funcs.append('cosh')
funcs.append('tanh')
funcs.append('sin')
funcs.append('cos')
funcs.append('tan')
funcs.append('exp')
funcs.append('log')
funcs.append('factorial')
symbols_str = [str(symbol) for symbol in self.symbols]
for func in funcs:
end_indices = [m.end() for m in re.finditer(func, trafo)]
while len(end_indices) != 0:
num_brackets = 0
for counter, c in enumerate(trafo[end_indices[0]:]):
if c == '(':
num_brackets += 1
elif c == ')':
num_brackets -= 1
if num_brackets == 0:
bracket_expression = trafo[end_indices[0]+1:end_indices[0]+counter]
if bracket_expression in symbols_str:
index = symbols_str.index(bracket_expression)
check = " if (!Units.convertible(Axis.fromSet(axes, " + str(index) + ").unit(), Units.EMPTY_UNIT)) {\n"
check += " throw new IllegalArgumentException(\"The unit of dimension " + str(index) + " (%s) needs to be effectively dimensionless.\"\n"
check += " .formatted(Axis.fromSet(axes, " + str(index) + ").unit()));\n"
check += " }\n"
self.__extra_symbol_check[index] = check
self.extra_imports.append("import eu.hoefel.unit.Units;")
trafo = trafo[:max(0, end_indices[0]-len(func)-1)] + trafo[end_indices[0]+counter+1:] # -1 due to the preceding operator sign (will fail if the preceding operator is a '**'
break
end_indices = [m.end() for m in re.finditer(func, trafo)]
def __remove_specific_funcs(self, expr):
"""
Removes specific functions (including their arguments) that do not change the units of the expression.
Parameters
----------
expr : sympy expression
The sympy expression to remove specific functions in
Returns
-------
sympy expression
the sympy expression with specific functions removed
"""
irrelevant_funcs_for_units = []
irrelevant_funcs_for_units.append(sym.functions.elementary.trigonometric.asin)
irrelevant_funcs_for_units.append(sym.functions.elementary.trigonometric.acos)
irrelevant_funcs_for_units.append(sym.functions.elementary.trigonometric.atan)
irrelevant_funcs_for_units.append(sym.functions.elementary.trigonometric.atan2)
irrelevant_funcs_for_units.append(sym.functions.elementary.trigonometric.acot)
irrelevant_funcs_for_units.append(sym.functions.elementary.hyperbolic.asinh)
irrelevant_funcs_for_units.append(sym.functions.elementary.hyperbolic.acosh)
irrelevant_funcs_for_units.append(sym.functions.elementary.hyperbolic.sinh)
irrelevant_funcs_for_units.append(sym.functions.elementary.hyperbolic.cosh)
irrelevant_funcs_for_units.append(sym.functions.elementary.hyperbolic.tanh)
irrelevant_funcs_for_units.append(sym.functions.elementary.trigonometric.sin)
irrelevant_funcs_for_units.append(sym.functions.elementary.trigonometric.cos)
irrelevant_funcs_for_units.append(sym.functions.elementary.trigonometric.tan)
irrelevant_funcs_for_units.append(sym.functions.elementary.exponential.exp)
irrelevant_funcs_for_units.append(sym.functions.elementary.exponential.log)
irrelevant_funcs_for_units.append(sym.functions.combinatorial.factorials.factorial)
for irrelevant_func_for_units in irrelevant_funcs_for_units:
# no idea why instanceof fails (╯°□°)╯︵ ┻━┻
if str(expr.func) == str(irrelevant_func_for_units):
return None
args = []
for arg in expr.args:
if self.__remove_specific_funcs(arg) is not None:
args.append(self.__remove_specific_funcs(arg))
if args == []: return expr
return expr.func(*args)
def __remove_irrelevant_funcs(self, expr):
"""
Removes functions (not their arguments, though!) that do not change the units of the variables within.
Parameters
----------
expr : sympy expression
The sympy expression to remove irrelevant functions in
Returns
-------
sympy expression
the sympy expression with all irrelevant functions (with respect to units) removed
"""
irrelevant_funcs_for_units = []
irrelevant_funcs_for_units.append(sym.functions.elementary.complexes.Abs)
irrelevant_funcs_for_units.append(sym.functions.elementary.integers.floor)
irrelevant_funcs_for_units.append(sym.functions.elementary.integers.ceiling)
irrelevant_funcs_for_units.append(sym.functions.elementary.miscellaneous.Min)
irrelevant_funcs_for_units.append(sym.functions.elementary.miscellaneous.Max)
for irrelevant_func_for_units in irrelevant_funcs_for_units:
# no idea why instanceof fails (╯°□°)╯︵ ┻━┻
if str(expr.func) == str(irrelevant_func_for_units):
return self.__remove_irrelevant_funcs(expr.args[0])
args = []
for arg in expr.args:
args.append(self.__remove_irrelevant_funcs(arg))
if args == []: return expr
return expr.func(*args)
def __collect_exponents(self, expr, symbols):
"""
Collects the exponents for the symbols in the given expression and adds them to the class-wide dict.
Parameters
----------
expr : sympy expression
The sympy expression to analyze.
symbols :
The list of sympy symbols
"""
# most likely we have a mul object on the outside now
# no idea why isinstance fails (╯°□°)╯︵ ┻━┻
if str(expr.func) == str(sym.core.mul.Mul):
for arg in expr.args:
if str(arg.func) == str(sym.core.power.Pow):
string_rep = sym.srepr(arg)
# we should have smth akin to Pow(Symbol('x'),Integer(2))
symbol, exponent = arg.args
index = symbols.index(symbol)
if '.' in str(exponent):
if index in self.dimension_exponents:
self.dimension_exponents[index] += float(str(exponent))
else:
self.dimension_exponents[index] = float(str(exponent))
else:
if index in self.dimension_exponents:
self.dimension_exponents[index] += float(str(exponent) + '.')
else:
self.dimension_exponents[index] = float(str(exponent) + '.')
elif str(arg.func) == str(sym.core.symbol.Symbol):
symbols_str = [str(symbol) for symbol in symbols]
if not str(arg) in symbols_str and str(arg) in self.extra_parameters and self.extra_parameters[str(arg)] == 'Constant':
key = str(arg)
else:
key = symbols_str.index(str(arg))
if key in self.dimension_exponents.keys():
self.dimension_exponents[key] += 1.0
else:
self.dimension_exponents[key] = 1.0
elif str(expr.func) == str(sym.core.power.Pow):
string_rep = sym.srepr(expr)
# we should have smth akin to Pow(Symbol('x'),Integer(2))
symbol, exponent = expr.args
if '.' in str(exponent):
self.dimension_exponents[symbols.index(symbol)] = float(str(exponent))
else:
self.dimension_exponents[symbols.index(symbol)] = float(str(exponent) + '.')
elif str(expr.func) == str(sym.core.symbol.Symbol):
symbols_str = [str(symbol) for symbol in symbols]
if not str(expr) in symbols_str and str(expr) in self.extra_parameters and self.extra_parameters[str(expr)] == 'Constant':
self.dimension_exponents[str(expr)] = 1.0
else:
self.dimension_exponents[symbols_str.index(str(expr))] = 1.0
else:
print("---------")
print("expr is " + str(expr))
print("expr func is " + str(expr.func))
print("Found type: " + str(type(expr.func)) + " for " + str(expr))
print("---------")
raise Exception("Cannot handle unit transformation (maybe too complex equation?)")
def __keep_one_summand(self, expr):
"""
Keeps one summand only.
Parameters
----------
expr : sympy expression
The sympy expression to keep one summand only.
Returns
-------
sympy expression
the sympy expression with all except one summand removed
"""
args = []
if isinstance(expr, sym.core.add.Add):
return expr.args[0]
else:
for arg in expr.args:
if isinstance(arg, sym.core.add.Add):
args.append(arg.args[0])
else:
args.append(self.__keep_one_summand(arg))
if args == []: return expr
return expr.func(*args)
def __build_to_base_transformation_point(self):
"""
Attaches the Java code for a method allowing to transform a point in the current coordinates to the corresponding base coordinate system.
"""
self.code += " @Override\n"
self.code += " public double[] toBasePoint(double[] position) {\n"
if self.__use_validate_position:
self.code += " validatePosition(position);\n\n"
if self.to_base_point is None:
self.code += " throw new UnsupportedOperationException(\"Transformation not implemented!\")"
else:
self.code += " double[] pointInBase = new double[" + str(self.g.dim()) + "];\n"
for i in range(self.g.dim()):
code, extra_imports = self.symbolic_to_java(self.to_base_point[i],self.symbols, extra_symbols=self.extra_parameters)
self.code += " pointInBase[" + str(i) + "] = " + code + ";\n"
self.extra_imports.extend(extra_imports)
self.code += " return pointInBase;\n"
self.code += " }\n"
self.code += "\n"
def __build_from_base_transformation_point(self):
"""
Attaches the Java code for a method allowing to transform a point in corresponding base coordinates to the current coordinate system.
"""
self.code += " @Override\n"
self.code += " public double[] fromBasePoint(double[] position) {\n"
if not self.unable_to_invert and self.from_base_point is None:
self.unable_to_invert, self.from_base_point, self.base_symbols = self.__invert_forward_transformation()
if self.to_base_point is None or self.unable_to_invert:
self.code += " throw new UnsupportedOperationException(\"Transformation not implemented!\")\n"
else:
self.code += " double[] pointInCurrentSystem = new double[" + str(self.dim) + "];\n"
for i in range(self.dim):
code, extra_imports = self.symbolic_to_java(self.from_base_point[i],self.base_symbols, extra_symbols=self.extra_parameters)
self.code += " pointInCurrentSystem[" + str(i) + "] = " + code + ";\n"
self.extra_imports.extend(extra_imports)
self.code += " return pointInCurrentSystem;\n"
self.code += " }\n"
self.code += "\n"
def __invert_forward_transformation(self):
"""
Inverts the given to_base_point transformation, i.e. it finds the transformation for a point given
in base coordinates to the current coordinate system.
Returns
-------
unable_to_invert
True if there was any failure in inverting
self.from_base_point
The resulting inverse transformation or None if not successful
self.base_symbols
The symbols corresponding to the inverse transformation
"""
if self.from_base_point is None:
unable_to_invert = False
try:
if self.base_symbols is None:
print("changing base symbols...")
self.base_symbols = [i.as_dummy() for i in self.g.symbols]
print("Inverting forward transformation...")
inv_results = sym.solve([t[0] - t[1] for t in zip(self.base_symbols, self.to_base_point)], list(self.symbols), dict=True)[0]
self.from_base_point = [sym.trigsimp(inv_results[s].simplify()) for s in self.symbols]
except Exception as e:
unable_to_invert = True
self.from_base_point = None
self.base_symbols = None
print("inversion failed: " + str(e))
else:
unable_to_invert = False # effectively false as given by user or previously calculated
return unable_to_invert, self.from_base_point, self.base_symbols
def __build_to_base_transformation_vector(self):
"""
Attaches the Java code to transform a vector from the current coordinate system to the corresponding base coordinate system.
"""
self.code += " @Override\n"
self.code += " public double[] toBaseVector(double[] position, double[] vector) {\n"
if self.__use_validate_position:
self.code += " validatePosition(position);\n\n"
if self.to_base_point is None:
self.code += " throw new UnsupportedOperationException(\"Transformation not implemented!\")"
else:
self.code += " double[] vectorInBaseSys = new double[vector.length];\n"
vec = []
for i in range(self.dim):
for j in range(self.dim):
expr = self.to_base_point[j].diff(self.symbols[i]).simplify()
if expr == 0: continue
if expr == 1:
expr_as_string = "vector[" + str(j) + "]"
else:
code, extra_imports = self.symbolic_to_java(expr, self.symbols, extra_symbols=self.extra_parameters)
expr_as_string = code + "*vector[" + str(j) + "]"
self.extra_imports.extend(extra_imports)
if len(vec) <= i:
vec.append(expr_as_string)
else:
vec[i] += "+" + expr_as_string
if vec[i] != 0:
self.code += " vectorInBaseSys[" + str(i) + "] = " + vec[i] + ";\n"
self.code += " return vectorInBaseSys;\n"
self.code += " }\n"
self.code += "\n"
def __build_from_base_transformation_vector(self):
"""
Attaches the Java code to transform a vector from the corresponding base coordinate system to the current coordinate system.
"""
self.code += " @Override\n"
self.code += " public double[] fromBaseVector(double[] position, double[] vector) {\n"
if not self.unable_to_invert and self.from_base_point is None:
self.unable_to_invert, self.from_base_point, self.base_symbols = self.__invert_forward_transformation()
if self.to_base_point is None or self.unable_to_invert:
self.code += " throw new UnsupportedOperationException(\"Transformation not implemented!\")"
else:
self.code += " double[] vectorInCurrentSys = new double[vector.length];\n"
vec = []
for i in range(self.g.dim()):
for j in range(self.g.dim()):
expr = self.from_base_point[j].diff(self.base_symbols[i])
if len(str(expr)) < 75:
expr = expr.simplify() # sympy might get stuck (or just take forever) for too long expressions
if expr == 0: continue
if expr == 1:
expr_as_string = "vector[" + str(j) + "]"
else:
code, extra_imports = self.symbolic_to_java(expr,self.base_symbols, extra_symbols=self.extra_parameters)
expr_as_string = code + "*vector[" + str(j) + "]"
self.extra_imports.extend(extra_imports)
if len(vec) <= i:
vec.append(expr_as_string)
elif not expr_as_string.startswith('-'):
vec[i] += "+" + expr_as_string
else:
vec[i] += expr_as_string
if vec[i] != 0:
self.code += " vectorInCurrentSys[" + str(i) + "] = " + vec[i] + ";\n"
self.code += " return vectorInCurrentSys;\n"
self.code += " }\n"
self.code += "\n"
def __build_metric_tensor(self):
"""
Attaches the Java code for the method to calculate the metric tensor to the code.
"""
self.code += " @Override\n"
self.code += " public double[][] metricTensor(double[] position, TensorTransformation behavior) {\n"
if self.__use_validate_position:
self.code += " validatePosition(position);\n\n"
self.code += " int dim = " + str(self.g.dim()) + ";\n"
self.code += " double[][] g = new double[dim][dim];\n"
self.code += "\n"
self.code += " // Note that we skip all elements that are zero anyways\n"
# check whether the same elements in covariant and covariant entries are nonnull
sameElementsAreNonNull = True
for i in range(self.g.dim()):
for j in range(self.g.dim()):
if (self.g.gdd[i,j] != 0 and self.g.guu[i,j] == 0) or (self.g.gdd[i,j] == 0 and self.g.guu[i,j] != 0):
sameElementsAreNonNull = False
else:
# Continue if the inner loop wasn't broken.
continue
# Inner loop was broken, break the outer.
break
if self.g.gdd != self.g.guu and not sameElementsAreNonNull:
self.code += " return switch (behavior) {\n"
self.code += " case COVARIANT -> {\n"
for i in range(self.g.dim()):
for j in range(self.g.dim()):
if self.g.gdd[i,j] == 0: continue
self.code += " g[" + str(i) + "][" + str(j) + "] = metricCoefficient(position, behavior, " + str(i) + ", " + str(j) +");\n"
self.code += " return g;\n"
self.code += " }\n"