Compare commits

..

No commits in common. "9b5356f8e7bf3e33b3eb457cd79ed43a1e18871a" and "956de5f9e34375a02d12fea42119bd65fed8e720" have entirely different histories.

19 changed files with 127 additions and 134 deletions

View file

@ -49,7 +49,7 @@ Repeater {
*/
property var positionPicker
readonly property var textTypes: ['Domain', 'string', 'number', 'int']
readonly property var textTypes: ['Domain', 'string', 'number']
readonly property var comboBoxTypes: ['ObjectType', 'Enum']
readonly property var listTypes: ['List', 'Dict']
@ -102,16 +102,13 @@ Repeater {
height: 30
label: propertyLabel
icon: `settings/custom/${propertyIcon}.svg`
min: propertyType == "int" ? 0 : -Infinity
isInt: propertyType == "int"
isDouble: propertyType == "number"
defValue: obj[propertyName] == null ? '' : obj[propertyName].toString()
category: {
return {
"Domain": "domain",
"string": "all",
"number": "all",
"int": "all",
"number": "all"
}[propertyType]
}
onChanged: function(newValue) {
@ -119,8 +116,7 @@ Repeater {
var newValueParsed = {
"Domain": () => MathLib.parseDomain(newValue),
"string": () => newValue,
"number": () => newValue,
"int": () => newValue
"number": () => parseFloat(newValue)
}[propertyType]()
// Ensuring old and new values are different to prevent useless adding to history.

View file

@ -261,7 +261,7 @@ BaseDialog {
authors: [authors.comradekingu, authors.Ad5001]
})
append({
tranName: '🇪🇸 ' + qsTr('Spanish'),
tranName: '🇳🇴 ' + qsTr('Spanish'),
link: 'https://hosted.weblate.org/projects/logarithmplotter/logarithmplotter/es/',
authors: [authors.IngrownMink4, authors.gallegonovato]
})

View file

@ -127,15 +127,12 @@ Item {
selectByMouse: true
onEditingFinished: function() {
if(insertButton.focus || insertPopup.focus) return
let value = text
if(control.isInt) {
let parsed = parseInt(value)
value = isNaN(parsed) ? control.min : Math.max(control.min,parsed)
} else if(control.isDouble) {
let parsed = parseFloat(value)
value = isNaN(parsed) ? control.min : Math.max(control.min,parsed)
}
if(value !== "" && value.toString() != defValue) {
var value = text
if(control.isInt)
value = isNaN(parseInt(value)) ? control.min : Math.max(control.min,parseInt(value))
if(control.isDouble)
value = isNaN(parseFloat(value)) ? control.min : Math.max(control.min,parseFloat(value))
if(value != "" && value.toString() != defValue) {
control.changed(value)
defValue = value.toString()
}

View file

@ -291,7 +291,7 @@ class CanvasAPI extends Module {
} else {
for(let x = 1; x < this.axesSteps.x.maxDraw; x += 1) {
let drawX = x*this.axesSteps.x.value
let txtX = this.axesSteps.x.expression.simplify(x).toString().replace(/^\((.+)\)$/, '$1')
let txtX = this.axesSteps.x.expression.simplify(x).replace(/^\((.+)\)$/, '$1')
let textHeight = this.measureText(txtX).height
this.drawVisibleText(txtX, this.x2px(drawX)-4, axisxpx+this.textsize/2+textHeight)
this.drawVisibleText('-'+txtX, this.x2px(-drawX)-4, axisxpx+this.textsize/2+textHeight)
@ -301,7 +301,7 @@ class CanvasAPI extends Module {
if(this.showygrad) {
for(let y = 0; y < this.axesSteps.y.maxDraw; y += 1) {
let drawY = y*this.axesSteps.y.value
let txtY = this.axesSteps.y.expression.simplify(y).toString().replace(/^\((.+)\)$/, '$1')
let txtY = this.axesSteps.y.expression.simplify(y).replace(/^\((.+)\)$/, '$1')
textWidth = this._ctx.measureText(txtY).width
this.drawVisibleText(txtY, axisypx-6-textWidth, this.y2px(drawY)+4+(10*(y===0)))
if(y !== 0)

View file

@ -199,7 +199,6 @@ export class Range extends Domain {
}
includes(x) {
if(x instanceof Expression) x = x.execute()
if(typeof x == 'string') x = executeExpression(x)
return ((this.openBegin && x > this.begin.execute()) || (!this.openBegin && x >= this.begin.execute())) &&
((this.openEnd && x < this.end.execute()) || (!this.openEnd && x <= this.end.execute()))
@ -258,19 +257,16 @@ export class SpecialDomain extends Domain {
}
includes(x) {
if(x instanceof Expression) x = x.execute()
if(typeof x == 'string') x = executeExpression(x)
return this.isValid(x)
}
next(x) {
if(x instanceof Expression) x = x.execute()
if(typeof x == 'string') x = executeExpression(x)
return this.nextValue(x)
}
previous(x) {
if(x instanceof Expression) x = x.execute()
if(typeof x == 'string') x = executeExpression(x)
return this.prevValue(x)
}
@ -319,7 +315,6 @@ export class DomainSet extends SpecialDomain {
}
includes(x) {
if(x instanceof Expression) x = x.execute()
if(typeof x == 'string') x = executeExpression(x)
for(let value of this.values)
if(x === value.execute()) return true
@ -327,7 +322,6 @@ export class DomainSet extends SpecialDomain {
}
next(x) {
if(x instanceof Expression) x = x.execute()
if(typeof x == 'string') x = executeExpression(x)
if(x < this.executedValues[0]) return this.executedValues[0]
for(let i = 1; i < this.values.length; i++) {
@ -339,7 +333,6 @@ export class DomainSet extends SpecialDomain {
}
previous(x) {
if(x instanceof Expression) x = x.execute()
if(typeof x == 'string') x = executeExpression(x)
if(x > this.executedValues[this.executedValues.length-1])
return this.executedValues[this.executedValues.length-1]

View file

@ -29,14 +29,8 @@ export class Expression {
throw new Error('Expression parser not initialized.')
if(!Modules.Objects)
throw new Error('Objects API not initialized.')
if(typeof expr === "string") {
this.expr = Utils.exponentsToExpression(expr)
this.calc = Modules.ExprParser.parse(this.expr).simplify()
} else {
// Passed an expression here directly.
this.calc = expr.simplify()
this.expr = expr.toString()
}
this.cached = this.isConstant()
this.cachedValue = null
if(this.cached && this.allRequirementsFullfilled())
@ -78,8 +72,19 @@ export class Expression {
simplify(x) {
let expr = this.calc.substitute('x', x).simplify()
if(expr.evaluate() === 0) expr = '0'
return new Expression(expr)
if(expr.evaluate() === 0) return '0'
let str = Utils.makeExpressionReadable(expr.toString());
if(str !== undefined && str.match(/^\d*\.\d+$/)) {
if(str.split('.')[1].split('0').length > 7) {
// Likely rounding error
str = parseFloat(str.substring(0, str.length-1)).toString();
}
}
return str
}
duplicate() {
return new Expression(this.toEditableString())
}
toEditableString() {
@ -88,12 +93,6 @@ export class Expression {
toString(forceSign=false) {
let str = Utils.makeExpressionReadable(this.calc.toString())
if(str !== undefined && str.match(/^\d*\.\d+$/)) {
if(str.split('.')[1].split('0').length > 7) {
// Likely rounding error
str = parseFloat(str.substring(0, str.length-1)).toString();
}
}
if(str[0] !== '-' && forceSign) str = '+' + str
return str
}

View file

@ -52,9 +52,10 @@ export class Sequence extends Expr.Expression {
}
simplify(n = 1) {
if(!(n in this.calcValues))
if(n in this.calcValues)
return Utils.makeExpressionReadable(this.calcValues[n].toString())
this.cache(n)
return this.calcValues[n].toString()
return Utils.makeExpressionReadable(this.calcValues[n].toString())
}
cache(n = 1) {

View file

@ -36,28 +36,6 @@ class ObjectsAPI extends Module {
this.currentObjectsByName = {}
}
/**
* Creates a new name for an object, based on the allowedLetters.
* If variables with each of the allowedLetters is created, a subscript
* number is added to the name.
* @param {string} allowedLetters
* @param {string} prefix - Prefix to the name.
* @return {string} New unused name for a new object.
*/
getNewName(allowedLetters, prefix='') {
// Allows to get a new name, based on the allowed letters,
// as well as adding a sub number when needs be.
let newid = 0
let ret
do {
let letter = allowedLetters[newid % allowedLetters.length]
let num = Math.floor((newid - (newid % allowedLetters.length)) / allowedLetters.length)
ret = prefix + letter + (num > 0 ? textsub(num-1) : '')
newid += 1
} while(ret in this.currentObjectsByName)
return ret
}
/**
* Renames an object from its old name to the new one.
* @param {string} oldName - Current name of the object.

View file

@ -16,8 +16,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import Objects from "../objects.mjs"
import { DrawableObject } from "common.mjs"
import { API as ObjectsCommonAPI } from "common.mjs"
import Point from "point.mjs"
import Text from "text.mjs"
import Function from "function.mjs"
@ -29,29 +28,15 @@ import XCursor from "xcursor.mjs"
import Sequence from "sequence.mjs"
import RepartitionFunction from "repartition.mjs"
/**
* Registers the object obj in the object list.
* @param {DrawableObject} obj - Object to be registered.
*/
function registerObject(obj) {
// Registers an object to be used in LogarithmPlotter.
if(obj.prototype instanceof DrawableObject) {
if(!Objects.types[obj.type()])
Objects.types[obj.type()] = obj
} else {
console.error("Could not register object " + (obj?.type() ?? obj.constructor.name) + ", as it isn't a DrawableObject.")
}
}
if(Object.keys(Modules.Objects.types).length === 0) {
registerObject(Point)
registerObject(Text)
registerObject(Function)
registerObject(GainBode)
registerObject(PhaseBode)
registerObject(SommeGainsBode)
registerObject(SommePhasesBode)
registerObject(XCursor)
registerObject(Sequence)
registerObject(RepartitionFunction)
ObjectsCommonAPI.registerObject(Point)
ObjectsCommonAPI.registerObject(Text)
ObjectsCommonAPI.registerObject(Function)
ObjectsCommonAPI.registerObject(GainBode)
ObjectsCommonAPI.registerObject(PhaseBode)
ObjectsCommonAPI.registerObject(SommeGainsBode)
ObjectsCommonAPI.registerObject(SommePhasesBode)
ObjectsCommonAPI.registerObject(XCursor)
ObjectsCommonAPI.registerObject(Sequence)
ObjectsCommonAPI.registerObject(RepartitionFunction)
}

View file

@ -24,6 +24,59 @@ import {ensureTypeSafety, serializesByPropertyType} from "../parameters.mjs"
// This file contains the default data to be imported from all other objects
class ObjectsCommonAPI extends Module {
constructor() {
super('ObjectsCommon', [
Modules.Objects,
Modules.ExprParser,
Modules.Latex
])
}
/**
* Creates a new name for an object, based on the allowedLetters.
* If variables with each of the allowedLetters is created, a subscript
* number is added to the name.
* @param {string} allowedLetters
* @param {string} prefix - Prefix to the name.
* @return {string} New unused name for a new object.
*/
getNewName(allowedLetters, prefix='') {
// Allows to get a new name, based on the allowed letters,
// as well as adding a sub number when needs be.
let newid = 0
let ret
do {
let letter = allowedLetters[newid % allowedLetters.length]
let num = Math.floor((newid - (newid % allowedLetters.length)) / allowedLetters.length)
ret = prefix + letter + (num > 0 ? textsub(num-1) : '')
newid += 1
} while(ret in Objects.currentObjectsByName)
return ret
}
/**
* Registers the object obj in the object list.
* @param {DrawableObject} obj - Object to be registered.
*/
registerObject(obj) {
// Registers an object to be used in LogarithmPlotter.
// This function is called from autoload.mjs
if(obj.prototype instanceof DrawableObject) {
if(!Objects.types[obj.type()])
Objects.types[obj.type()] = obj
} else {
console.error("Could not register object " + (obj.type()) + ", as it isn't a DrawableObject.")
}
}
}
/** @type {ObjectsCommonAPI} */
Modules.ObjectsCommon = Modules.ObjectsCommon || new ObjectsCommonAPI()
export const API = Modules.ObjectsCommon
/**
* Class to extend for every type of object that
* can be drawn on the canvas.
@ -380,7 +433,7 @@ export class ExecutableObject extends DrawableObject {
* Returns the simplified expression string for a given x.
*
* @param {number} x
* @returns {string|Expression}
* @returns {string}
*/
simplify(x = 1) {return '0'}

View file

@ -17,8 +17,7 @@
*/
import { textsub } from "../utils.mjs"
import Objects from "../objects.mjs"
import { ExecutableObject } from "common.mjs"
import { API as Common, ExecutableObject } from "common.mjs"
import { parseDomain, Expression, SpecialDomain } from "../mathlib.mjs"
import * as P from "../parameters.mjs"
import Latex from "../math/latex.mjs"
@ -51,7 +50,7 @@ export default class Function extends ExecutableObject {
expression = 'x', definitionDomain = 'RPE', destinationDomain = 'R',
displayMode = 'application', labelPosition = 'above', labelX = 1,
drawPoints = true, drawDashedLines = true) {
if(name == null) name = Objects.getNewName('fghjqlmnopqrstuvwabcde')
if(name == null) name = Common.getNewName('fghjqlmnopqrstuvwabcde')
super(name, visible, color, labelContent)
if(typeof expression == 'number' || typeof expression == 'string') expression = new Expression(expression.toString())
this.expression = expression

View file

@ -21,7 +21,7 @@ import * as P from "../parameters.mjs"
import Objects from "../objects.mjs"
import Latex from "../math/latex.mjs"
import { ExecutableObject } from "common.mjs"
import { API as Common, ExecutableObject } from "common.mjs"
import Function from "function.mjs"
import { API as HistoryAPI } from "../history/common.mjs"
@ -43,7 +43,7 @@ export default class GainBode extends ExecutableObject {
constructor(name = null, visible = true, color = null, labelContent = 'name + value',
om_0 = '', pass = 'high', gain = '20', labelPosition = 'above', labelX = 1, omGraduation = false) {
if(name == null) name = Objects.getNewName('G')
if(name == null) name = Common.getNewName('G')
if(name === 'G') name = 'G₀' // G is reserved for sum of BODE magnitudes (Somme gains Bode).
super(name, visible, color, labelContent)
if(typeof om_0 == "string") {
@ -51,7 +51,7 @@ export default class GainBode extends ExecutableObject {
om_0 = Objects.currentObjectsByName[om_0]
if(om_0 == null) {
// Create new point
om_0 = Objects.createNewRegisteredObject('Point', [Objects.getNewName('ω'), true, this.color, 'name'])
om_0 = Objects.createNewRegisteredObject('Point', [Common.getNewName('ω'), true, this.color, 'name'])
HistoryAPI.addToHistory(new CreateNewObject(om_0.name, 'Point', om_0.export()))
om_0.update()
labelPosition = 'below'

View file

@ -19,11 +19,11 @@
import { executeExpression, Expression } from "../mathlib.mjs"
import * as P from "../parameters.mjs"
import Objects from "../objects.mjs"
import { API as HistoryAPI } from "../history/common.mjs"
import { CreateNewObject } from "../historylib.mjs"
import Latex from "../math/latex.mjs"
import { ExecutableObject } from "common.mjs"
import { API as Common, ExecutableObject } from "common.mjs"
import { API as HistoryAPI } from "../history/common.mjs"
import { CreateNewObject } from "../historylib.mjs"
export default class PhaseBode extends ExecutableObject {
@ -40,7 +40,7 @@ export default class PhaseBode extends ExecutableObject {
constructor(name = null, visible = true, color = null, labelContent = 'name + value',
om_0 = '', phase = 90, unit = '°', labelPosition = 'above', labelX = 1) {
if(name == null) name = Objects.getNewName('φ')
if(name == null) name = Common.getNewName('φ')
if(name === 'φ') name = 'φ₀' // φ is reserved for sum of BODE phases (Somme phases Bode).
super(name, visible, color, labelContent)
if(typeof phase == 'number' || typeof phase == 'string') phase = new Expression(phase.toString())
@ -50,7 +50,7 @@ export default class PhaseBode extends ExecutableObject {
om_0 = Objects.currentObjectsByName[om_0]
if(om_0 == null) {
// Create new point
om_0 = Objects.createNewRegisteredObject('Point', [Objects.getNewName('ω'), this.color, 'name'])
om_0 = Objects.createNewRegisteredObject('Point', [Common.getNewName('ω'), this.color, 'name'])
om_0.labelPosition = this.phase.execute() >= 0 ? 'above' : 'below'
HistoryAPI.history.addToHistory(new CreateNewObject(om_0.name, 'Point', om_0.export()))
labelPosition = 'below'
@ -88,7 +88,7 @@ export default class PhaseBode extends ExecutableObject {
return this.om_0.y.toString()
} else {
let newExp = this.om_0.y.toEditableString() + ' + ' + this.phase.toEditableString()
return new Expression(newExp)
return (new Expression(newExp)).toString()
}
}

View file

@ -18,10 +18,8 @@
import { Expression } from "../mathlib.mjs"
import * as P from "../parameters.mjs"
import Objects from "../objects.mjs"
import Latex from "../math/latex.mjs"
import { DrawableObject } from "common.mjs"
import { API as Common, DrawableObject } from "common.mjs"
export default class Point extends DrawableObject {
@ -38,7 +36,7 @@ export default class Point extends DrawableObject {
constructor(name = null, visible = true, color = null, labelContent = 'name + value',
x = 1, y = 0, labelPosition = 'above', pointStyle = '●') {
if(name == null) name = Objects.getNewName('ABCDEFJKLMNOPQRSTUVW')
if(name == null) name = Common.getNewName('ABCDEFJKLMNOPQRSTUVW')
super(name, visible, color, labelContent)
if(typeof x == 'number' || typeof x == 'string') x = new Expression(x.toString())
this.x = x

View file

@ -16,12 +16,10 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { API as Common, ExecutableObject } from "common.mjs"
import * as P from "../parameters.mjs"
import Objects from "../objects.mjs"
import Latex from "../math/latex.mjs"
import { ExecutableObject } from "common.mjs"
export default class RepartitionFunction extends ExecutableObject {
static type(){return 'Repartition'}
@ -48,7 +46,7 @@ export default class RepartitionFunction extends ExecutableObject {
constructor(name = null, visible = true, color = null, labelContent = 'name + value',
probabilities = {'0': '0'}, labelPosition = 'above', labelX = 1) {
if(name == null) name = Objects.getNewName('XYZUVW', "F_")
if(name == null) name = Common.getNewName('XYZUVW', "F_")
super(name, visible, color, labelContent)
this.probabilities = probabilities
this.labelPosition = labelPosition
@ -81,7 +79,7 @@ export default class RepartitionFunction extends ExecutableObject {
// Simplify returns the simplified string of the expression.
simplify(x = 1) {
return this.execute(x).toString()
return this.execute(x)
}
getLabel() {

View file

@ -19,9 +19,8 @@
import { Sequence as MathSequence, Domain } from "../mathlib.mjs"
import * as P from "../parameters.mjs"
import Latex from "../math/latex.mjs"
import Objects from "../objects.mjs"
import { ExecutableObject } from "common.mjs"
import { API as Common, ExecutableObject } from "common.mjs"
import Function from "function.mjs"
@ -46,7 +45,7 @@ export default class Sequence extends ExecutableObject {
constructor(name = null, visible = true, color = null, labelContent = 'name + value',
drawPoints = true, drawDashedLines = true, defaultExp = {1: "n"},
baseValues = {0: 0}, labelPosition = 'above', labelX = 1) {
if(name == null) name = Objects.getNewName('uvwPSUVWabcde')
if(name == null) name = Common.getNewName('uvwPSUVWabcde')
super(name, visible, color, labelContent)
this.drawPoints = drawPoints
this.drawDashedLines = drawDashedLines

View file

@ -18,10 +18,9 @@
import { Expression } from "../mathlib.mjs"
import * as P from "../parameters.mjs"
import Objects from "../objects.mjs"
import Latex from "../math/latex.mjs"
import { DrawableObject } from "common.mjs"
import { API as Common, DrawableObject } from "common.mjs"
export default class Text extends DrawableObject {
@ -42,7 +41,7 @@ export default class Text extends DrawableObject {
constructor(name = null, visible = true, color = null, labelContent = 'null',
x = 1, y = 0, labelPosition = 'center', text = 'New text', disableLatex = false) {
if(name == null) name = Objects.getNewName('t')
if(name == null) name = Common.getNewName('t')
super(name, visible, color, labelContent)
if(typeof x == 'number' || typeof x == 'string') x = new Expression(x.toString())
this.x = x

View file

@ -21,7 +21,7 @@ import * as P from "../parameters.mjs"
import Latex from "../math/latex.mjs"
import Objects from "../objects.mjs"
import { DrawableObject } from "common.mjs"
import { API as Common, DrawableObject } from "common.mjs"
export default class XCursor extends DrawableObject {
@ -33,7 +33,7 @@ export default class XCursor extends DrawableObject {
[QT_TRANSLATE_NOOP('prop','targetElement')]: new P.ObjectType('ExecutableObject', true),
[QT_TRANSLATE_NOOP('prop','labelPosition')]: P.Enum.Position,
[QT_TRANSLATE_NOOP('prop','approximate')]: 'boolean',
[QT_TRANSLATE_NOOP('prop','rounding')]: 'int',
[QT_TRANSLATE_NOOP('prop','rounding')]: 'number',
[QT_TRANSLATE_NOOP('prop','displayStyle')]: new P.Enum(
'— — — — — — —',
'⸺⸺⸺⸺⸺⸺',
@ -45,7 +45,7 @@ export default class XCursor extends DrawableObject {
constructor(name = null, visible = true, color = null, labelContent = 'name + value',
x = 1, targetElement = null, labelPosition = 'left', approximate = true,
rounding = 3, displayStyle = '— — — — — — —', targetValuePosition = 'Next to target') {
if(name == null) name = Objects.getNewName('X')
if(name == null) name = Common.getNewName('X')
super(name, visible, color, labelContent)
this.approximate = approximate
this.rounding = rounding
@ -77,10 +77,8 @@ export default class XCursor extends DrawableObject {
var t = this.targetElement
var approx = ''
if(this.approximate) {
approx = (t.execute(this.x.execute()))
let intLength = Math.round(approx).toString().length
let rounding = Math.min(this.rounding, approx.toString().length - intLength - 1)
approx = approx.toPrecision(rounding + intLength)
approx = t.execute(this.x.execute())
approx = approx.toPrecision(this.rounding + Math.round(approx).toString().length)
}
return `${t.name}(${this.name}) = ${t.simplify(this.x.toEditableString())}` +
(this.approximate ? ' ≈ ' + approx : '')
@ -90,13 +88,11 @@ export default class XCursor extends DrawableObject {
let t = this.targetElement
let approx = ''
if(this.approximate) {
approx = (t.execute(this.x.execute()))
let intLength = Math.round(approx).toString().length
let rounding = Math.min(this.rounding, approx.toString().length - intLength - 1)
approx = approx.toPrecision(rounding + intLength)
approx = t.execute(this.x.execute())
approx = approx.toPrecision(this.rounding + Math.round(approx).toString().length)
}
let simpl = t.simplify(this.x.toEditableString())
return `${Latex.variable(t.name)}(${Latex.variable(this.name)}) = ${simpl.latexMarkup ? simpl.latexMarkup : Latex.variable(simpl)}` +
return `${Latex.variable(t.name)}(${Latex.variable(this.name)}) = ${simpl.tokens ? Latex.expression(simpl.tokens) : simpl}` +
(this.approximate ? ' \\simeq ' + approx : '')
}

View file

@ -272,6 +272,8 @@ export function makeExpressionReadable(str) {
[/_([\d\w+-]+)/g, function(match, p1) { return textsub(p1) }],
[/\[([^\[\]]+)\]/g, function(match, p1) { return textsub(p1) }],
[/(\d|\))×/g, '$1'],
//[/×(\d|\()/g, '$1'],
[/([^a-z])\(([^)(+.\/-]+)\)/g, "$1×$2"],
[/integral\((.+),\s?(.+),\s?["'](.+)["'],\s?["'](.+)["']\)/g, function(match, a, b, p1, body, p2, p3, by, p4) {
if(a.length < b.length) {
return `${textsub(a)}${textsup(b)} ${body} d${by}`