def __init__(self):
     self.CONTAINER_ID = 1448455
     # Wouldn't be needed if we were using the api throughout
     # See comments around its use
     self.api = p2api.ApiConnection('demo', 52052, 'tutorial')
     # TODO Consider a way of hiding this
     self.P2API_SECRET_DATA = {"username": "******", "password": "******"}
     self.P2API_BASE_URL = "https://www.eso.org/copdemo/api/"
Example #2
0
    def connect(self, username=None, password=None):
        """ Return an API to interact with remote observation proposals"""
        # At present time only ESO P2 API is available for real use

        # api is None if fake one has not been requested by option
        # TODO add logging  instead of self.ui.ShowInfoMessage("create API for %s" % self.apiName)
        if self.apiName:
            self.api = FakeAPI(username, password, self.ui)
        else:
            import p2api
            if username == '52052':
                type = 'demo'
            else:
                type = 'production'
            self.api = p2api.ApiConnection(type, username, password)

        return self.api
Example #3
0
    def connectAPI(self, username, password, ob):
        import p2api
        if username == '52052':
            type = 'demo'
        else:
            type = 'production'
        try:
            self.api = p2api.ApiConnection(type, username, password)
            # TODO test that api is ok and handle error if any...

            runs, _ = self.api.getRuns()
            self.ui.fillTree(runs)

            self.setConnected(True)
            self.username = username
            self.ui.showTreeFrame(ob)
        except:
            self.ui.addToLog("Can't connect to P2 (see LOG).")
            trace = traceback.format_exc()
            self.ui.addToLog(trace, False)
Example #4
0
    def connectAPI(self, username, password, ob):
        if username == TUTORIAL_LOGIN:  # or username == JMMC_LOGIN:
            self.apitype = DEMO_APITYPE
        else:
            self.apitype = PRODUCTION_APITYPE
        try:
            logger.info("Connecting to p2 api...")
            self.api = p2api.ApiConnection(self.apitype, username, password)

            self.ui.addToLog("Connected to p2 api (%s)" % self.apitype)
            # TODO test that api is ok and handle error if any...

            self.refreshTree()

            self.setConnected(True)
            self.username = username
            self.ui.showTreeFrame(ob)
        except:
            self.ui.ShowErrorMessage("Can't connect to P2 (see LOG).")
            trace = traceback.format_exc()
            self.ui.addToLog(trace, False, level=logging.ERROR)
def test_delete_finding_chart():
    # connect to the API
    api = p2api.ApiConnection('demo', '52052', 'tutorial')

    # create observing block
    ob, _ = api.createOB(1448455, 'dummy observing block')
    ob_id = ob['obId']

    # add finding chart
    api.addFindingChart(ob_id, 'images/fc1.jpg')
    api.addFindingChart(ob_id, 'images/fc2.jpg')

    charts, _ = api.getFindingChartNames(ob_id)

    assert len(charts) == 2, 'Should have two finding charts'

    # delete 1st finding chart
    api.deleteFindingChart(ob_id, 1)

    charts, _ = api.getFindingChartNames(ob_id)

    assert len(charts) == 1, 'Should have two finding charts'
    assert charts[0] == 'fc2.jpg', 'Should keep the 2nd finding chart'
Example #6
0
def make_fc(
    p2uid=None,
    pswd=None,
    obids=[],
    bk_images=[],
    bk_lams=[],
    data_loc=os.path.join('.', 'fcm_data'),
    plot_loc=os.path.join('.', 'fcm_plots'),
    do_pdf=True,
    do_png=False,
    no_upload=False,
    systemtex=False,
    montage=False,
    clear_SkyView_cache=False,
    obsdate=None,
    do_parang=False,
    demo=False,
):
    '''
   The main fcmaker function, to create finding charts from p2.
   
   Args:
      p2uid: string. P2 user ID (will prompt if is None)
      pswd:  string. P2 user password (will prompt if is None)
      obids: list of int. List of the P2 OB ID for which to generate finding charts
      bk_images: list of string. Specify the FC background: SkyView survey name, None for default, or local FITS filename
      bk_lams: list of string. Specify the wavelength of the background charts. None to read from FITS header.
      data_loc: string. Relative path to the background images (local FITS files or SkyView images).
      plot_loc: string. Relative path to the background images (local FITS files or SkyView images).
      do_pdf: bool. Save a local PDF file ?
      do_png: bool. Save a local png file ?
      no_upload: bool. Skip the upload of finding charts to p2 ?
      systemtex: bool. Use the system Latex instead of the Python latex ?
      montage: bool. Use of Montage to rotate the fields with North up ?
      clear_SkyView_cache: bool. Clear the SkyView cache ?
      obsdate: string. Year (Month, Day, Hour, Minute, ...) of the observation
      do_parang: bool. Show the instrument field-of-view when a parallactic angle is required ?
      demo: bool. Connect to the demo p2 server to process test OBs ? Will override p2uid and pswd.
   '''

    starttime = datetime.now()

    # Make sure I have at least one obids listed if not in local mode
    if len(obids) == 0:
        obids = [eval(input('OB Id from p2: '))]

    # Make some safety checks
    if not (type(bk_images) == list):
        raise Exception('Ouch! bk_images must be a list !')
    if not (type(bk_lams) == list):
        raise Exception('Ouch! bk_lams must be a list !')
    if not (type(obids) == list):
        raise Exception('Ouch! obids must be a list !')

    # Set the observing date (and time)
    set_obsdate(obsdate)

    # Set the generic parameters for fcmaker
    set_fcmaker(systemtex, montage, clear_SkyView_cache, data_loc, plot_loc,
                do_parang)

    # If I need to connect to p2, extract the user ID and obIDs.
    # If no password or user ID in file, ask for it now.
    if (p2uid is None) and not (demo):
        p2uid = input('p2 user ID: ')

    if (pswd is None) and not (demo):
        pswd = getpass.getpass('Password: '******'Ouch! Please specify one bk_image for each obID!')

    else:
        bk_images = [None] * len(obids)

    # Idem for the associated wavelengths
    if len(bk_lams) > 0:

        # Make sure I have a bk_lam specified for each ob Id !
        if len(bk_lams) != len(obids):
            raise Exception('Ouch! Please specify one bk_lam for each obID!')

    else:
        bk_lams = [None] * len(obids)

    #  Log into p2
    if demo:
        # Go into the demo server
        api = p2api.ApiConnection('demo', '52052', 'tutorial', False)
    else:
        # Go into the production area
        api = p2api.ApiConnection('production', p2uid, pswd, False)

    # Clear the password right away, for security reasons
    pswd = None

    #  Now, start doing stuff
    for (o, obID) in enumerate(obids):

        print(' ')  # Some space for clarity

        # Step 1: extract the OB parameters
        print('%i: fetching the OB parameters ...' % (obID))
        # Fetch all the parameters required for the finding chart
        fc_params = fcm_id.get_p2fcdata(obID, api)

        # Step 2: create the finding chart
        print('%i: creating the finding chart ...' % (obID))
        # Send these to the plotting routine
        fc_fn = fcm_p.draw_fc(fc_params,
                              bk_image=bk_images[o],
                              bk_lam=bk_lams[o],
                              do_pdf=do_pdf,
                              do_png=do_png)

        # Step 3: upload the chart to p2
        # If the no_upload flag is set, keep going right away
        if no_upload:
            continue

        # Ok, let's start looking at the finding charts online
        # List existing finding charts already attached to the OB
        fcNames, _ = api.getFindingChartNames(obID)

        # Are there any finding charts over there ?
        if len(fcNames) > 0:

            print('   Existing finding charts:')
            for i in range(5):
                if i < len(fcNames):
                    print('    %i: %s' % ((i + 1), fcNames[i]))
                else:
                    print('    %i: empty' % ((i + 1)))
            answer = None
            while not (answer in range(0, 6)):
                answer = eval(
                    input('   Which slot to upload to (1-5; 0 = no upload)? '))

        else:
            # If no finding charts exist, then just put it in the first spot (no need to ask)
            print(
                '   No finding chart in the OB (yet): using slot 1 for upload ...'
            )
            answer = 1

        # Check if the finding chart slot is busy ... do we want to replace it ?
        if answer == 0:
            fill = 'n'
        elif answer <= len(fcNames):
            fill = None
            while not (fill in ['y', 'n']):
                fill = input(
                    '   Finding chart slot occupied: overwrite (y/n)? ')
        else:
            fill = 'y'

        if fill == 'y':
            # If I have to delete the existing finding chart
            if answer <= len(fcNames):
                api.deleteFindingChart(
                    obID, answer)  # p2 finding chart index start at 1

            # And upload the new chart
            api.addFindingChart(obID, fc_fn)

    print('All finding charts done in %.1f seconds.' %
          ((datetime.now() - starttime).total_seconds()))