Beispiel #1
0
def main(argv=None, MainWindow=None):
    """Run madgui mainloop and exit process when finished."""
    import madgui.core.config as config
    from madgui.core.session import Session
    from docopt import docopt
    if MainWindow is None:
        from madgui.widget.mainwindow import MainWindow
    app = init_app(argv)
    # Filter arguments understood by Qt before doing our own processing:
    args = app.arguments()[1:]
    opts = docopt(__doc__, args, version=__version__)
    conf = config.load(opts['--config'])
    config.number = conf.number
    session = Session(conf)
    try:
        window = MainWindow(session)
        session.window.set(window)
        window.show()
        # Defer `loadDefault` to avoid creation of a AsyncRead thread before
        # the main loop is entered: (Being in the mainloop simplifies
        # terminating the AsyncRead thread via the QApplication.aboutToQuit
        # signal. Without this, if the setup code excepts after creating the
        # thread the main loop will never be entered and thus aboutToQuit
        # never be emitted, even when pressing Ctrl+C.)
        QTimer.singleShot(0, partial(session.load_default, opts['FILE']))
        exit_code = app.exec_()
    finally:
        session.terminate()
    return sys.exit(exit_code)
Beispiel #2
0
def test_session_destroyed(app):
    session = Session()
    session.load_model('sample_model/sample.cpymad.yml')
    model = session.model()
    session.terminate()
    assert session.model() is None
    assert model.madx is None
Beispiel #3
0
    def session(cls, model_file, record_files):
        from madgui.core.session import Session
        from madgui.core.config import load as load_config
        from glob import glob
        if isinstance(record_files, str):
            record_files = glob(record_files, recursive=True)

        config = load_config(isolated=True)
        session = Session(config)
        session.load_model(model_file, stdout=False, undo_stack=UndoStack())
        model = session.model()
        measured = OrbitResponse.load(model, record_files)
        analysis = cls(model, measured)
        analysis.session = session
        return analysis
Beispiel #4
0
def session(app):
    config = load_config(isolated=True)
    session = Session(config)
    session.control._settings.update({
        'shot_interval': 0.001,
        'jitter': True,
        'auto_params': True,
        'auto_sd': True,
    })
    return session
Beispiel #5
0
def test_session_load_model(app):
    session = Session()
    path = session.find_model('sample_model/')
    assert path.endswith('sample.cpymad.yml')
    session.load_model(path)
    model = session.model()
    assert model.seq_name == 'beamline1'
Beispiel #6
0
def main(args=None):
    opts = docopt(__doc__, args)
    model_path = opts['--model'] or '../hit_models/hht3'

    init_app(['madgui'])

    blacklist = opts['--blacklist'] or [
        's4mu1e', 's4mu2e',
        's3me2e', 's3mu1a', 's3ms1v',
        's0qg4d', 's0qg1f',
    ]

    def blacklisted(name):
        return name in blacklist or any(b in name for b in blacklist)

    config = load_config(isolated=True)
    session = Session(config)
    session.load_model(model_path, stdout=False)
    model = session.model()

    by_type = get_elements_by_type(model)

    if opts['--twiss']:
        print('')
        print('############')
        print('## TWISS  ##')
        print('############')
        print('\n'.join(get_twiss_args_errors()))

    if opts['--ealign']:
        print('')
        print('############')
        print('## EALIGN ##')
        print('############')
        for base_name in sorted(by_type):
            print('')
            print('# {}'.format(base_name))
            for elem in by_type[base_name]:
                if not blacklisted(elem):
                    print('\n'.join(get_ealign_errors(elem)))

    if opts['--knobs']:
        print('')
        print('############')
        print('## KNOBS  ##')
        print('############')

        for base_name in sorted(by_type):
            print('')
            print('# {}'.format(base_name))
            for elem in by_type[base_name]:
                if not blacklisted(elem):
                    print('\n'.join(get_knob_errors(model, elem)))

    if opts['--attr']:
        print('')
        print('############')
        print('## ATTRS  ##')
        print('############')
        for spec in opts['--attr']:
            type_, attrs = spec.split('->', 1)
            attrs = attrs.split('/')
            for elem in model.elements:
                if elem.base_name == type_:
                    print('\n'.join(
                        '{}->{}'.format(elem.name, attr) for attr in attrs))
Beispiel #7
0
def test_empty_session(app):
    session = Session()
    session.terminate()
Beispiel #8
0
def main(model_file, spec_file, record_file):
    """
    Usage:
        analysis MODEL PARAMS RECORDS

    MODEL must be the path of the model/sequence file to initialize MAD-X.

    PARAMS is a YAML file with arguments for the "measurement" procedure, it
        must contain at least a list of `monitors` and `optics` and should
        contain keys for errors to be inserted: `knobs`, `ealign`, `efcomp`

    RECORDS is the name of the YAML output file where
    """
    init_app([], gui=False)

    config = load_config(isolated=True)
    with ExitStack() as stack:
        setup_args = yaml.load_file(spec_file)['procedure']
        session = stack.enter_context(Session(config))
        session.control._settings.update({
            'shot_interval':
            0.001,
            'jitter':
            setup_args.get('jitter', True),
            'auto_params':
            False,
            'auto_sd':
            True,
        })
        session.load_model(model_file,
                           stdout=False,
                           command_log=lambda text: print("X:>", text))
        session.control.set_backend('hit_acs.plugin:TestACS')
        session.control.connect()
        session.control.write_all()
        corrector = Corrector(session)
        corrector.setup({
            'monitors': setup_args['monitors'],
            'optics': setup_args['optics'],
        })

        # FIXME: this is not yet compatible with general parameter errors. In
        # order to fix this, the hit_acs test backend will have to use an
        # independent model!
        model = session.model()
        import_errors(model, setup_args['errors'])
        model.twiss.invalidate()

        corrector.set_optics_delta(setup_args.get('optics_deltas', {}),
                                   setup_args.get('default_delta', 1e-4))
        corrector.open_export(record_file)

        widget = mock.Mock()
        procbot = ProcBot(widget, corrector)

        num_mons = len(setup_args['monitors'])
        num_optics = len(setup_args['optics']) + 1
        if setup_args.get('jitter', True):
            num_ignore = setup_args.get('num_ignore', 1)
            num_shots = setup_args.get('num_shots', 5)
        else:
            num_ignore = 0
            num_shots = 1

        procbot.start(num_ignore, num_shots, gui=False)

        total_steps = num_mons * (num_optics + 1) * (num_ignore + num_shots)

        i = 0
        while procbot.running and i < 2 * total_steps:
            procbot._feed(None, None)
            time.sleep(0.010)
            i += 1

        assert not procbot.running
Beispiel #9
0
 def __init__(self, app):
     self.session = Session()
     self.loadModel()
     self.model = self.session.model()
     self.globs = self.model.globals
Beispiel #10
0
class EmittanzRechner:
    def __init__(self, app):
        self.session = Session()
        self.loadModel()
        self.model = self.session.model()
        self.globs = self.model.globals

    def loadStrengths(self, filename):
        self.model.load_strengths(filename)

    def loadModel(self):
        self.session.load_model(modelPath, stdout=False)

    def getSecMap(self, initElem, endElem):
        return self.model.sectormap(initElem, endElem)

    def _buildMats(self, secMaps):
        Mx = [[m[0][0]**2, m[0][1] * m[0][0] * 2, m[0][1]**2] for m in secMaps]

        My = [[m[2][2]**2, m[2][3] * m[2][2] * 2, m[2][3]**2] for m in secMaps]
        return Mx, My

    def computeTwiss(self, sig11, sig12, sig22):
        em2 = sig11 * sig22 - sig12**2
        if em2 < 0.:
            return [0.] * 3
        beta = sig11 / np.sqrt(em2)
        alpha = -sig12 / np.sqrt(em2)
        gamma = sig22 / np.sqrt(em2)
        return [beta, alpha, gamma]

    def computeEmit(self, sig11, sig12, sig22):
        em2 = sig11 * sig22 - sig12**2
        if em2 < 0.:
            return 0.
        return np.sqrt(em2)

    def _solveLinEqs(self, M, x):
        Mt = np.transpose(M)
        M = np.matmul(np.linalg.inv(np.matmul(Mt, M)), Mt)
        return np.matmul(M, x)

    def threeMonsMethod(self, data):
        """
        @param array data: should have the following structure
               [[monitor1, [sigx1 , sigy1]],
                [monitor2, [sigx2 , sigy2]],
                [monitor3, [sigx3 , sigy3]]]
        """
        mes = np.array(data)
        mes = np.transpose(mes)
        mons = mes[0]
        beam = mes[1]

        secMaps = [self.getSecMap('hht3$start', mi) for mi in mons]

        Mx, My = self._buildMats(secMaps)
        x, y = [b[0] for b in beam], [b[1] for b in beam]

        solx = self._solveLinEqs(Mx, x)
        soly = self._solveLinEqs(My, y)

        return self.computeEmit(*solx), self.computeEmit(*soly)

    def sample(self, mu, sig, N=1000):
        return np.random.normal(mu, sig, N)

    def gauss(self, x, mu, sig, A):
        return A * np.exp(-(x - mu)**2 / (2 * sig**2))

    def moyal(self, x, mu, sig, A):
        return A * np.exp(-((x - mu) / sig + np.exp(-(x - mu) / sig)) / 2)

    def _showMonteCarl(self, emx, emy):
        print('RESULTS:')
        print('emx: {} +- {}'.format(*emx))
        print('emy: {} +- {}'.format(*emy))

    def _plotTwissx(self, twiss):
        twiss = np.transpose(twiss)
        plt.figure('Beta_x')

        beta = twiss[0]
        mask = beta < 200.
        beta_masked = beta[mask]
        b = plt.hist(beta_masked, bins=100)
        x = (b[1][:-1] + b[1][1:]) / 2

        mu = np.mean(beta)
        sig = np.std(beta)
        A = max(b[0])

        popt, pcov = curve_fit(self.moyal, x, b[0], p0=[mu, sig, A])
        print('Beta:')
        print()
        print(popt)
        print()

        x = np.linspace(0, 100, 200)

        plt.plot(x, self.moyal(x, *popt))

        plt.figure('Alpha_x')

        alf = twiss[1]
        alf = alf[twiss[0] < 200.]
        a = plt.hist(alf, bins=100)

        popt = self.fitData(alf, moyalFit=True)
        x = -a[1]
        plt.plot(-x, self.moyal(x, *popt))
        print('Alpha')
        print()
        print(popt)
        plt.show()

    def _plotTwissy(self, twiss):

        bety_max = 15.
        twiss = np.transpose(twiss)
        plt.figure('Beta_x')

        beta = twiss[0]
        mask = beta < bety_max
        beta_masked = beta[mask]
        b = plt.hist(beta_masked, bins=100)
        x = (b[1][:-1] + b[1][1:]) / 2

        mu = np.mean(beta)
        sig = np.std(beta)
        A = max(b[0])

        popt, pcov = curve_fit(self.moyal, x, b[0], p0=[mu, sig, A])
        print('Beta_y:')
        print()
        print(popt)
        print()

        x = np.linspace(0, bety_max, 200)

        plt.plot(x, self.moyal(x, *popt))

        plt.figure('Alpha_y')

        alfy_max = 1.
        alf = twiss[1]
        alf = alf[twiss[1] < alfy_max]
        a = plt.hist(alf, bins=100)
        x = (a[1][:-1] + a[1][1:]) / 2

        mu = np.mean(alf)
        sig = np.std(alf)
        A = max(a[0])

        popt, pcov = curve_fit(self.moyal, x, a[0], p0=[mu, sig, A])

        x = np.linspace(-1., 3, 200)
        plt.plot(x, self.moyal(x, *popt))
        print('Alpha')
        print()
        print(popt)
        plt.show()

    def fitData(self, g, moyalFit=False):
        h = plt.hist(g, bins=100)
        x = (h[1][:-1] + h[1][1:]) / 2
        y = h[0]

        if moyalFit:
            x *= -1
            mu = np.mean(x)
            sig = np.std(x)
            A = max(y)

            p = [mu, sig, A]
            popt, pcov = curve_fit(self.moyal, x, y, p0=p)
        else:
            mu = np.mean(x)
            sig = np.std(x)
            A = max(y)
            p = [mu, sig, A]
            popt, pcov = curve_fit(self.gauss, x, y, p0=p)

        return popt

    def monteCarl(self, data, unc, plot=False):
        mes = np.array(data)
        mes = np.transpose(mes)
        mons = mes[0]
        beam = mes[1]
        N = 100000

        xSample = [
            self.sample(beam[i][0], unc[i][0], N) for i in range(len(beam))
        ]
        ySample = [
            self.sample(beam[i][1], unc[i][1], N) for i in range(len(beam))
        ]

        xSample = np.transpose(xSample)
        ySample = np.transpose(ySample)

        secMaps = [self.getSecMap('hht3$start', mi) for mi in mons]
        Mx, My = self._buildMats(secMaps)

        solx = [self._solveLinEqs(Mx, x) for x in xSample]
        emx = np.array([self.computeEmit(*sx) for sx in solx])
        twx = np.array([self.computeTwiss(*sx) for sx in solx])
        soly = [self._solveLinEqs(My, y) for y in ySample]
        emy = np.array([self.computeEmit(*sy) for sy in soly])
        twy = np.array([self.computeTwiss(*sy) for sy in soly])

        twx = twx[emx > 0.]
        twy = twy[emy > 0.]
        emx = emx[emx > 0.]
        emy = emy[emy > 0.]

        fitx = self.fitData(emx * 1e6)
        fity = self.fitData(emy * 1e6, moyalFit=True)
        self._showMonteCarl(fitx[:2], fity[:2])
        self._plotTwissx(twx)
        self._plotTwissy(twy)

        if plot:
            plt.cla()
            plt.figure(1)
            plt.xlabel(r'$\varepsilon_x$ [mm mrad]')
            h = plt.hist(emx * 1e6, bins=100, alpha=0.6)
            x = np.linspace(0., max(h[1]), 200)
            plt.plot(x, self.gauss(x, *fitx))
            print('Emx')
            print(fitx)

            plt.figure(2)
            plt.xlabel(r'$\varepsilon_y$ [mm mrad]')
            h = plt.hist(emy * 1e6, bins=100, alpha=0.6)
            x = np.linspace(0., max(h[1]), 200)
            x *= -1
            plt.plot(-x, self.moyal(x, *fity))
            print('Emy')
            print(fity)
            plt.show()