Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Add optimization to SRO #1404

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/sr-frontend/src/app/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
import Character from './Character'
import CharacterSelector from './CharacterSelector'
import Database from './Database'
import Optimize from './Optimize'
import { theme } from './Theme'

export default function App() {
Expand All @@ -26,6 +27,7 @@ export default function App() {
<Stack gap={1} pt={1}>
<CharacterSelector />
<Character />
<Optimize />
<Database />
</Stack>
</CalcProvider>
Expand Down
142 changes: 142 additions & 0 deletions apps/sr-frontend/src/app/Optimize.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import type { RelicSlotKey } from '@genshin-optimizer/sr-consts'
import type { ICachedRelic } from '@genshin-optimizer/sr-db'
import type { Read } from '@genshin-optimizer/sr-formula'
import { convert, selfTag } from '@genshin-optimizer/sr-formula'
import { OptimizeForNode } from '@genshin-optimizer/sr-opt'
import { useCalcContext, useDatabaseContext } from '@genshin-optimizer/sr-ui'
import { CardThemed, DropdownButton } from '@genshin-optimizer/ui-common'
import { range } from '@genshin-optimizer/util'
import {
Box,
Button,
CardContent,
Container,
Grid,
MenuItem,
Stack,
Typography,
} from '@mui/material'
import { useCallback, useMemo, useState } from 'react'

type Build = {
value: number
relicIds: string[]
}

export default function Optimize() {
const { database } = useDatabaseContext()

const { calc } = useCalcContext()

const [numWorkers, setNumWorkers] = useState(8)

// Step 1: Pick formula(s); anything that `calc.compute` can handle will work
const [optTarget, setOptTarget] = useState<Read | undefined>(undefined)

const relicsBySlot = useMemo(
() =>
database.relics.values.reduce(
(relicsBySlot, relic) => {
relicsBySlot[relic.slotKey].push(relic)
return relicsBySlot
},
{
head: [],
hand: [],
feet: [],
body: [],
sphere: [],
rope: [],
} as Record<RelicSlotKey, ICachedRelic[]>
),
[database.relics.values]
)

const [build, setBuild] = useState<Build | undefined>(undefined)

const optimize = useCallback(async () => {
if (!optTarget || !calc) return
const results = await OptimizeForNode(
calc,
optTarget,
relicsBySlot,
numWorkers
)
setBuild({
value: results[0].best,
relicIds: Object.values(results[0].bestIds),
})
}, [calc, numWorkers, optTarget, relicsBySlot])

const member0 = convert(selfTag, { member: 'member0', et: 'self' })

return (
<Container>
<CardThemed bgt="dark">
<CardContent>
<Stack>
<Typography variant="h5">Optimize</Typography>
<Box>
<DropdownButton
title={`Optimization Target${
optTarget ? `: ${optTarget.tag.name || optTarget.tag.q}` : ''
}`}
>
{calc?.listFormulas(member0.listing.formulas).map((read) => (
<MenuItem
key={read.tag.name || read.tag.q}
onClick={() => setOptTarget(read)}
>
{read.tag.name || read.tag.q}
</MenuItem>
))}
</DropdownButton>
<DropdownButton title={`Num Workers: ${numWorkers}`}>
{range(1, 16).map((n) => (
<MenuItem key={n} onClick={() => setNumWorkers(n)}>
{n} worker(s)
</MenuItem>
))}
</DropdownButton>
<Button onClick={optimize}>Optimize</Button>
</Box>
<Box>
<Typography>Best: {build?.value}</Typography>
<Grid container columns={5} gap={1}>
{build?.relicIds.map((id) => {
const relic = database.relics.get(id)
return (
<Grid item xs={1} key={id}>
<Relic relic={relic} />
</Grid>
)
})}
</Grid>
</Box>
</Stack>
</CardContent>
</CardThemed>
</Container>
)
}

function Relic({ relic }: { relic: ICachedRelic | undefined }) {
return (
<Stack>
{!relic ? (
<Typography>Empty</Typography>
) : (
<Box>
<Typography>
Main: {relic.mainStatKey} - {relic.mainStatVal}
</Typography>
{relic.substats.map((substat) => (
<Typography key={substat.key}>
Sub: {substat.key} - {substat.value}
</Typography>
))}
</Box>
)}
</Stack>
)
}
14 changes: 7 additions & 7 deletions apps/sr-frontend/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@ export default defineConfig({
},

// Uncomment this if you are using workers.
// worker: {
// plugins: [
// viteTsConfigPaths({
// root: '../../',
// }),
// ],
// },
worker: {
plugins: [
viteTsConfigPaths({
root: '../../',
}),
],
},
})
2 changes: 1 addition & 1 deletion libs/pando/src/node/optimization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import type {
* `OP` redeclaration here.
*/
type OP = Exclude<TaggedOP, 'tag' | 'dtag' | 'vtag'>
type NumTagFree = NumNode<OP>
export type NumTagFree = NumNode<OP>
type StrTagFree = StrNode<OP>
type AnyTagFree = AnyNode<OP>

Expand Down
18 changes: 18 additions & 0 deletions libs/sr-opt/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"extends": ["../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
}
]
}
7 changes: 7 additions & 0 deletions libs/sr-opt/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# sr-opt

This library was generated with [Nx](https://nx.dev).

## Running unit tests

Run `nx test sr-opt` to execute the unit tests via [Jest](https://jestjs.io).
11 changes: 11 additions & 0 deletions libs/sr-opt/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/* eslint-disable */
export default {
displayName: 'sr-opt',
preset: '../../jest.preset.js',
testEnvironment: 'node',
transform: {
'^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
},
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: '../../coverage/libs/sr-opt',
}
30 changes: 30 additions & 0 deletions libs/sr-opt/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "sr-opt",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "libs/sr-opt/src",
"projectType": "library",
"targets": {
"lint": {
"executor": "@nx/linter:eslint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": ["libs/sr-opt/**/*.ts"]
}
},
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "libs/sr-opt/jest.config.ts",
"passWithNoTests": true
},
"configurations": {
"ci": {
"ci": true,
"codeCoverage": true
}
}
}
},
"tags": []
}
2 changes: 2 additions & 0 deletions libs/sr-opt/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './optimize'
export * from './worker'
73 changes: 73 additions & 0 deletions libs/sr-opt/src/optimize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { detach } from '@genshin-optimizer/pando'
import {
allRelicSetKeys,
type RelicSlotKey,
} from '@genshin-optimizer/sr-consts'
import type { ICachedRelic } from '@genshin-optimizer/sr-db'
import type { Calculator, Read, Tag } from '@genshin-optimizer/sr-formula'
import { range } from '@genshin-optimizer/util'
import type { OptimizeMessageDone } from './worker'
import { type OptimizeMessage } from './worker'
// TODO: maybe change this to sr-srod's IRelic, and return the relic objs, rather than IDs?
export async function OptimizeForNode(
calc: Calculator,
optTarget: Read,
relicsBySlot: Record<RelicSlotKey, ICachedRelic[]>,
numWorkers: number
) {
// Step 2: Detach nodes from Calculator
const relicSetKeys = new Set(allRelicSetKeys)
const detachedNodes = detach([optTarget], calc, (tag: Tag) => {
if (tag['member'] !== 'member0') return undefined // Wrong member
if (tag['et'] !== 'self') return undefined // Not applied (only) to self

if (tag['src'] === 'dyn' && tag['qt'] === 'premod') return { q: tag['q']! } // Art stat bonus
if (tag['q'] === 'count' && relicSetKeys.has(tag['src'] as any))
return { q: tag['src']! } // Art set counter
return undefined
})

const chunkSize = Math.ceil(relicsBySlot.head.length / numWorkers)
// Calculate results on workers
const workers = range(1, numWorkers).map(
() =>
new Worker(new URL('./worker.ts', import.meta.url), {
type: 'module',
})
)
// Wait for all workers to finish
const results = await Promise.all(
workers.map((worker, index) => {
return new Promise<OptimizeMessageDone>((res, rej) => {
// On worker completion, resolve promise
worker.onmessage = ({ data }: MessageEvent<OptimizeMessage>) => {
console.log(data)
if (data.resultType === 'done') {
res(data)
} else rej()
}
// Chunk data
const chunkedRelicsBySlot: Record<RelicSlotKey, ICachedRelic[]> = {
head: relicsBySlot.head.slice(
index * chunkSize,
(index + 1) * chunkSize
),
hand: relicsBySlot.hand,
body: relicsBySlot.body,
feet: relicsBySlot.feet,
sphere: relicsBySlot.sphere,
rope: relicsBySlot.rope,
}
// Start worker
worker.postMessage({
command: 'optimize',
relicsBySlot: chunkedRelicsBySlot,
optTarget,
detachedNodes,
})
})
})
)

return results.sort((a, b) => a.best - b.best)
}
Loading