summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/scripts/lua-physical/physical-quantity.lua
blob: d89fdd2836b4984703f276ddc9828669a93cd695 (plain)
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
--[[
This file contains the quantity class

Copyright (c) 2020 Thomas Jenni

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]--

local prefix = ... and (...):match '(.-%.?)[^%.]+$' or ''
local D = require(prefix..'physical-dimension')
local U = require(prefix..'physical-unit')
local N = require(prefix..'physical-number')

-- Quantity class
local Quantity = {}
Quantity.__index = Quantity

-- make Quantity table callable
setmetatable(Quantity, {
	__call = function(class, ...)
		return Quantity.new(...)
	end
})


-- registry for base units
Quantity._base = {}

-- registry for prefixes
Quantity._prefixes = {}

-- modes for the function tosiunitx()
Quantity.SIUNITX_SI = 0
Quantity.SIUNITX_num = 1
Quantity.SIUNITX_si = 2


-- constructor
function Quantity.new(q)

	local p = {}
	setmetatable(p, Quantity)
	
	-- copy constructor
	if getmetatable(q) == Quantity then
		p.dimension = q.dimension
		p.value = q.value
		p.basefactor = q.basefactor
		p.unit = U(q.unit)

	-- create a dimensionless Quantity
	else
		p.dimension = D.new()
		p.value = q or 1
		p.basefactor = 1
		p.unit = U()
	end
	
	return p
end


-- create base quantities
function Quantity.defineBase(symbol,name,dimension)

	if rawget(_G,"_"..symbol) ~= nil then
		error("Error: Quantity '_"..symbol.."' does already exist.")
	end

	local p = Quantity.new()
	p.value = 1
	p.dimension = dimension
	p.unit = U.new(symbol,name)

	table.insert(Quantity._base,p)
	
	rawset(_G, "_"..symbol, p)

	return p
end


-- create derived quantities
function Quantity.define(symbol, name, q)

	-- check if quantity does already exist
	if rawget(_G,"_"..symbol) ~= nil then
		error("Error: Quantity '_"..symbol.."' does already exist.")
	end

	-- check if given value is a quantity
	if getmetatable(q) ~= Quantity then
		error("Error: No quantity given in the definition of '"..name.."'.")
	end
	
	local p = Quantity.new(q)
	
	if name ~= nil then
		p.value = 1
		p.basefactor = q.basefactor * q.value
		p.unit = U.new(symbol, name)
	else
		local p = Quantity.new(q)
	end

	rawset(_G, "_"..symbol, p)

	return p
end


-- define a prefix
function Quantity.definePrefix(symbol,name,factor)

	-- check if prefix does already exist
	if Quantity._prefixes[symbol] ~= nil then
		error("Error: Prefix '"..symbol.."' does already exist.")
	end

	-- append prefix to the _prefixes table
	Quantity._prefixes[symbol] = {
		symbol=symbol,
		name=name, 
		factor=factor
	}
end


-- create prefixed versions of the given units
function Quantity.addPrefix(prefixes, qs)
	
	-- todo: what if prefixes and units are no lists?

	for i=1,#prefixes do
		local prefix = Quantity._prefixes[prefixes[i]]

		for j=1,#qs do
			local q = qs[j]

			local p = Quantity.new(q)
			p.unit = U.new(q.unit.symbol, q.unit.name, prefix.symbol, prefix.name)
			p.basefactor = p.basefactor*prefix.factor

			-- assert that unit does not exist
			local symbol = "_"..prefix.symbol..q.unit.symbol
			if rawget(_G,symbol) ~= nil then
				error("Error: Cannot create prefixed Quantity, because '"..symbol.."' does already exist.")
			end

			-- set unit as a global variable
			rawset(_G, symbol, p)
		end
	end
end


-- Add two quantities
function Quantity.__add(q1, q2)
	
	if getmetatable(q1) ~= Quantity then
		q1 = Quantity.new(q1)
	end
	if getmetatable(q2) ~= Quantity then
		q2 = Quantity.new(q2)
	end

	if q1.dimension ~= q2.dimension then
		error("Error: Cannot add '"..tostring(q1).."' to '"..tostring(q2).."', because they have different dimensions.")
	end

	-- convert o1 to q2 units
	local p = q1:to(q2)
	p.value =  p.value + q2.value

	return 	p
end


-- subtract a dimension from another one
function Quantity.__sub(q1, q2)

	if getmetatable(q1) ~= Quantity then
		q1 = Quantity.new(q1)
	end
	if getmetatable(q2) ~= Quantity then
		q2 = Quantity.new(q2)
	end

	if q1.dimension ~= q2.dimension then
		error("Error: Cannot subtract '"..tostring(q2).."' from '"..tostring(q1).."', because they have different dimensions.")
	end

	-- convert q1 to q2 units
	local p = q1:to(q2)
	p.value =  p.value - q2.value

	return 	p
end


-- unary minus
function Quantity.__unm(q)
	local p = Quantity.new(q)
	p.value = -p.value
	return p
end


-- multiply a dimension by a number
function Quantity.__mul(q1, q2)

	if getmetatable(q1) ~= Quantity then
		q1 = Quantity.new(q1)
	end
	if getmetatable(q2) ~= Quantity then
		q2 = Quantity.new(q2)
	end
	
	local p = Quantity.new()

	p.dimension = q1.dimension * q2.dimension
	p.value = q1.value * q2.value
	p.basefactor = q1.basefactor * q2.basefactor
	p.unit = q1.unit * q2.unit

	return p
end


-- divide a quantity / number by a quantity / number
function Quantity.__div(q1, q2)
	
	if getmetatable(q1) ~= Quantity then
		q1 = Quantity.new(q1)
	end
	if getmetatable(q2) ~= Quantity then
		q2 = Quantity.new(q2)
	end
	
	local p = Quantity.new()
	
	p.dimension = q1.dimension / q2.dimension
	p.value = q1.value / q2.value
	p.basefactor = q1.basefactor / q2.basefactor
	p.unit = q1.unit / q2.unit

	return p
end

-- power
function Quantity.__pow(q1,q2)

	if getmetatable(q1) ~= Quantity then
		q1 = Quantity.new(q1)
	end
	if getmetatable(q2) ~= Quantity then
		q2 = Quantity.new(q2)
	end

	if not q2.dimension:iszero() then
		error("Error: Cannot take the power of '"..tostring(q1).."', because the exponent '"..tostring(q2).."' is not dimensionless.")
	end

	local p = Quantity.new()
	local e = q2:to()

	p.value = q1.value^e.value
	
	e = e:__tonumber()
	p.dimension = q1.dimension^e
	p.basefactor = q1.basefactor^e
	p.unit = q1.unit^e
	
	return p
end

-- test if two quantities are equal
function Quantity.__eq(q1,q2)

	if getmetatable(q1) ~= Quantity then
		q1 = Quantity.new(q1)
	end
	if getmetatable(q2) ~= Quantity then
		q2 = Quantity.new(q2)
	end
	
	local p = q1:to(q2)

	if p.value ~= q2.value then
		return false
	elseif p.dimension ~= q2.dimension then
		return false
	elseif p.basefactor ~= q2.basefactor then
		return false
	end

	return true
end

-- check if this quantity is less than another one
function Quantity.__lt(q1,q2)

	if getmetatable(q1) ~= Quantity then
		q1 = Quantity.new(q1)
	end
	if getmetatable(q2) ~= Quantity then
		q2 = Quantity.new(q2)
	end

	if q1.dimension ~= q2.dimension then
		error("Error: Cannot compare '"..tostring(q1).."' to '"..tostring(q2).."', because they have different dimensions.")
	end

	return q1:to().value < q2:to().value
end

-- check if this quantity is close to another one. r is the maximal relative deviation.
function Quantity:isclose(q, r)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if getmetatable(r) ~= Quantity then
		r = Quantity.new(r)
	end

	if self.dimension ~= q.dimension then
		error("Error: Cannot compare '"..tostring(self).."' to '"..tostring(q)..", because they have different dimensions.")
	end
	if not r.dimension:iszero() then
		error("Error. The argument '"..tostring(r).."' of the isclose function is not unitless.")
	end
	
	local q1 = self:to():__tonumber()
	local q2 = q:to():__tonumber()
	local r = r:to():__tonumber()
	
	local delta = math.abs(q1 - q2)
	local min = math.min(math.abs(q1),math.abs(q2))
	return  (delta / min) <= r
end


-- convert quantity to another unit
function Quantity:to(q)

	local p = Quantity.new()

	-- convert to base units
	p.dimension = self.dimension
	p.value = self.value * self.basefactor

	-- convert to target units
	if q ~= nil then
		if getmetatable(q) ~= Quantity then
			q = Quantity.new(q)
		end

		if self.dimension ~= q.dimension then
			error("Error: Cannot convert '"..tostring(self).."' to '"..tostring(q).."', because they have different dimensions.")
		end

		p.value = p.value / q.basefactor
		p.basefactor = q.basefactor
		p.unit = U(q.unit)
	
	-- convert to base units
	else
		local unit = U.new()
		local base = Quantity._base

		for i=1,#base do
			unit = unit * base[i].unit^self.dimension[i]
		end
		
		p.unit = unit
	end

	return p
end


-- convert quantity to a number
function Quantity:__tonumber()
	if type(self.value) == "number" then
		return self.value
	else
		return self.value:__tonumber()
	end
end


-- convert quantity to a string
function Quantity:__tostring()
	return tostring(self.value)..tostring(self.unit)
end


-- convert quantity to an siunitx expression
function Quantity:tosiunitx(param,mode)

	mode = mode or self.SIUNITX_SI
	param = param or ""

	if param ~= "" then
		param = "["..param.."]"
	end

	if mode == Quantity.SIUNITX_SI then
		return "\\SI"..param.."{"..tostring(self.value).."}".."{"..self.unit:tosiunitx().."}"

	elseif mode == Quantity.SIUNITX_num then
		return "\\num"..param.."{"..tostring(self.value).."}"

	elseif mode == Quantity.SIUNITX_si then
		return "\\si"..param.."{"..self.unit:tosiunitx().."}"

	else
		error("Error: Unknown mode '"..tostring(mode).."'.")
	end

end


-- minimum value
function Quantity.min(q,...)
	
	for _,p in ipairs({...}) do
		if p < q then
			q = p
		end
    end

    return Quantity.new(q)
end


-- maximum value
function Quantity.max(q,...)
	
	for _,p in ipairs({...}) do
		if p > q then
			q = p
		end
    end

    return Quantity.new(q)
end


-- absolute value
function Quantity.abs(q)
	
	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if q.value < 0 then
		return -q
	else
		return q
	end
end


-- square root
function Quantity.sqrt(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	return q^0.5
end


-- logarithm
function Quantity.log(q, base)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the logarithm function is not unitless.")
	end

	
	local b = nil
	if base ~= nil then
		if getmetatable(base) ~= Quantity then
			base = Quantity.new(base)
		end

		b = base:to():__tonumber()
	end


	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.log(q:to().value, b)
	else
		p.value = q:to().value:log(b)
	end

	return p
end


-- exponential function
function Quantity.exp(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the exponential function is not unitless.")
	end
	
	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.exp(q:to().value)
	else
		p.value = q:to().value:exp()
	end

	return p
end


-- TRIGONOMETRIC FUNCTIONS
-- https://en.wikipedia.org/wiki/Trigonometric_functions

-- sine
function Quantity.sin(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the sine function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.sin(q:to().value)
	else
		p.value = q:to().value:sin()
	end

	return p
end


-- cosine
function Quantity.cos(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the cosine function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.cos(q:to().value)
	else
		p.value = q:to().value:cos()
	end

	return p
end


-- tangent
function Quantity.tan(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the tangent function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.tan(q:to().value)
	else
		p.value = q:to().value:tan()
	end
	
	return p
end


-- arcus sine
function Quantity.asin(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the arcus sine function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.asin(q:to().value)
	else
		p.value = q:to().value:asin()
	end
	
	return p
end


-- arcus cosine
function Quantity.acos(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the arcus cosine function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.acos(q:to().value)
	else
		p.value = q:to().value:acos()
	end
	
	return p
end


-- arcus tangent
function Quantity.atan(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the arcus tangent function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.atan(q:to().value)
	else
		p.value = q:to().value:atan()
	end
	
	return p
end


-- HYPERBOLIC FUNCTIONS
-- https://en.wikipedia.org/wiki/Hyperbolic_function

-- hyperbolic sine
function Quantity.sinh(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the sine hyperbolicus function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = 0.5 * math.exp(q.value) - 0.5 / math.exp(q.value)
	else
		p.value = q:to().value:sinh()
	end
	
	return p
end


-- hyperbolic cosine
function Quantity.cosh(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the cosine hyperbolicus function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = 0.5 * math.exp(q.value) + 0.5 / math.exp(q.value)
	else
		p.value = q:to().value:cosh()
	end
	
	return p
end


-- hyperbolic tangent
function Quantity.tanh(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the tangent hyperbolicus function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = (math.exp(q.value) - math.exp(-q.value)) / (math.exp(q.value) + math.exp(-q.value))
	else
		p.value = q:to().value:tanh()
	end
	
	return p
end


-- INVERS HYPERBOLIC FUNCTIONS
-- https://en.wikipedia.org/wiki/Inverse_hyperbolic_function

-- inverse hyperbolic sine
-- (-inf < q < +inf)
function Quantity.asinh(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the inverse sine hyperbolicus function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.log(q.value + math.sqrt(q.value^2 + 1))
	else
		p.value = q:to().value:asinh()
	end
	
	return p
end


-- inverse hyperbolic cosine
-- (1 < q)
function Quantity.acosh(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the inverse cosine hyperbolicus function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.log(q.value + math.sqrt(q.value^2 - 1))
	else
		p.value = q:to().value:acosh()
	end
	
	return p
end


-- inverse hyperbolic tangent
-- (-1 < q < 1)
function Quantity.atanh(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the inverse tangent hyperbolicus function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = 0.5 * math.log((1 + q.value)/(1 - q.value))
	else
		p.value = q:to().value:atanh()
	end
	
	return p
end


return Quantity