Exemplo n.º 1
0
    def get_info(self, **args):
        # ========================
        ''' Retrieve information about the selected variable '''

        try:
            wid = args["wid"]
        except:
            wid = None

        # --- Units
        try:
            self.units = self.nc.variables[self.varname].getncattr('units')
        except:
            self.units = ''

        # --- Fill or missing value
        try:
            self.missing = self.nc.variables[self.varname].getncattr(
                '_FillValue')
        except:
            try:
                self.missing = self.nc.variables[self.varname].getncattr(
                    'missing_value')
            except:
                self.missing = None

        tools.toconsola('Missing value: ' + '%s' % self.missing + '\n',
                        wid=wid)
Exemplo n.º 2
0
 def download(self):
     #=================
     theurl = self.filename(self.PATH_LOAD)
     toconsola('FETCHING ' + theurl, wid=self.cons)
     #print('FETCHING ',theurl)
     filename = wget.download(theurl)
     print('')
Exemplo n.º 3
0
 def saidin_hour(self):
     #====================
     name = self.filename(self.PATH)
     if not empty(name):
         self.FILENAME.set(name)
         self.preview()
     else:
         toconsola('No image selected', wid=self.cons)
         #print('No image selected')
         self.FILENAME.set('')
Exemplo n.º 4
0
    def done(self):
        #=================
        '''Gets the selected options and gets the corresponding URL before closing the app.
       The URL is saved in self.FILENAME'''

        if empty(self.FILENAME.get()):
            messagebox.showinfo(message='No image selected')
            return
        toconsola('SAIDIN FILE = ' + self.FILENAME.get(), wid=self.cons)
        #print('SAIDIN FILE = ',self.FILENAME.get())
        self.destroy()
Exemplo n.º 5
0
    def request(self):
        #=================
        '''Sends the request to scan the page contents'''
        '''
    if self.regbox.get() == "eastmed":
      toconsola("Eastern Mediterranean soon available",wid=self.cons)
      #print("Eastern Mediterranean soon available")
      region ="westmed"
      self.REGION.set(self.regbox.get())
      self.PATH       = 'http://cooweb.cmima.csic.es/thredds/dodsC/'+self.REGION.get()+"/"
      self.PATH_LOAD  = 'http://cooweb.cmima.csic.es/thredds/fileServer/'+self.REGION.get()+"/"
      self.request()
      return
    '''
        region = self.regbox.get()
        self.REGION.set(region)
        self.PATH = 'http://cooweb.cmima.csic.es/thredds/dodsC/' + region + "/"
        self.PATH_LOAD = 'http://cooweb.cmima.csic.es/thredds/fileServer/' + region + "/"
        #PATH = 'http://cooweb.cmima.csic.es/saidin-js/jsoncontrolservlet?service=search&'
        PATH = "http://cooweb.cmima.csic.es/" + self.JS_LIST[
            region] + "/jsoncontrolservlet?service=search&"
        year = self.YEAR.get()
        month = self.MONTH.get()
        day = self.DAY.get()

        startDate = 'startDate=' + '%02d/' % month + '%02d/' % day + str(year)
        endDate = 'endDate=' + '%02d/' % month + '%02d/' % day + str(year)
        URL = PATH + startDate + '&' + endDate
        toconsola('Requesting ' + URL, wid=self.cons)
        #print('Requesting ',URL)
        res = requests.get(URL)
        r = res.json()
        r['search'].pop('startDate')
        r['search'].pop('endDate')
        files = [row for row in r['search'].keys()]

        if len(files) == 0:
            messagebox.showinfo(message='No images available')
            return

        hour = [files[i].split('.')[1] for i in range(0, len(files))]
        sat = [files[i].split('.')[2] for i in range(0, len(files))]
        s = sorted(zip(hour, sat))
        self.SEL = [
            e[0][0:2] + ':' + e[0][2:4] + ' UTC (%s)' % self.dict[e[1]]
            for e in s
        ]
        self.SAT = [e[1] for e in s]
        self.hour_var.set(self.SEL[0])
        self.hourbox['values'] = self.SEL
        self.hourbox.configure(state='!disabled')
        #self.Bprev.configure(state='!disabled')
        self.saidin_hour()
Exemplo n.º 6
0
        def download():
            # ===============
            if self.MEDSEA.get():
                url = 'https://cosmo.icm.csic.es/climatology/MEDSEA_100.nc'
                message = 'Downloading ' + url
                toconsola(message, wid=wid)
                r = requests.get(url, verify=False)
                with open('MEDSEA_100.nc', 'wb') as f:
                    f.write(r.content)

            if self.GLOBCURRENT.get():
                url = 'https://cosmo.icm.csic.es/climatology/GLOBCURRENT_100.nc'
                message = 'Downloading ' + url
                toconsola(message, wid=wid)
                r = requests.get(url, verify=False)
                with open('GLOBCURRENT_100.nc', 'wb') as f:
                    f.write(r.content)

            if self.SEALEVEL.get():
                url = 'https://cosmo.icm.csic.es/climatology/SEALEVEL_100.nc'
                message = 'Downloading ' + url
                toconsola(message, wid=wid)
                r = requests.get(url, verify=False)
                with open('SEALEVEL_100.nc', 'wb') as f:
                    f.write(r.content)

            toconsola('Done !', wid=wid)
Exemplo n.º 7
0
    def get_grid(self, **args):
        # ========================
        ''' Get the grid of the axes from the netcdf file '''

        try:
            wid = args["wid"]
        except:
            wid = None

        if self.varid is None:
            tools.toconsola('Undefined variable,', wid=wid)
            return

        if self.icdf.withX and self.icdf.withY:
            self.with_axes = True
        else:
            self.with_axes = False

        if self.with_axes:

            self.x = self.nc.variables[self.icdf.xname][:]
            self.y = self.nc.variables[self.icdf.yname][:]

            if self.icdf.grid2d:
                self.xx = self.x
                self.yy = self.y
            else:
                self.xx, self.yy = np.meshgrid(self.x, self.y)

        else:

            self.x = np.arange(self.icdf.nx)
            self.y = np.arange(self.icdf.ny)
            self.xx, self.yy = np.meshgrid(self.x, self.y)

        self.xmin = float(np.min(self.x))
        self.xmax = float(np.max(self.x))
        self.ymin = float(np.min(self.y))
        self.ymax = float(np.max(self.y))
Exemplo n.º 8
0
    def read(self, K=0, L=0, **args):
        # =============================
        ''' Read 2D field from netcdf file and returns the data array'''

        try:
            wid = args["wid"]
        except:
            wid = None

        if self.varid is None:
            data = None
            tools.toconsola('Undefined variable,', wid=wid)
            return

        if self.ndims is None:
            data = None
            tools.toconsola('Undefined number of variable dimensions,',
                            wid=wid)
            return

        tools.toconsola('Reading, K, L = ' + str(K) + ', ' + str(L), wid=wid)

        if self.ndims == 2:
            data = self.nc.variables[self.varname][:, :]
        elif self.ndims == 3:
            if self.icdf.ppl[self.varid] > -1:
                data = self.nc.variables[self.varname][L, :, :].squeeze()
            elif CDF.icdf.ppk[self.varid] > -1:
                data = self.nc.variables[self.varname][K, :, :].squeeze()
            else:
                messagebox.showinfo(message='Invalid variable dimensions')
                data = None
                return
        elif self.ndims == 4:
            data = self.nc.variables[self.varname][L, K, :, :].squeeze()

        # Eliminate NaN values in field:
        fill_value = data.fill_value
        a = data.filled()
        a[np.isnan(a)] = fill_value
        data = np.ma.masked_equal(a, fill_value)

        # Check if the returned arrays is Masked Array:
        #if isinstance(data,np.ma.MaskedArray):
        #  pass
        #else:
        #  if self.missing is None:
        #    data = np.ma.masked_array(data)
        #  else:
        #    data = np.ma.masked_equal(data,self.missing)

        #self.minval = float(self.data.min())
        #self.maxval = float(self.data.max())
        #tools.toconsola('Min val = '+str(self.minval),wid=wid)
        #tools.toconsola('Max val = '+str(self.maxval),wid=wid)

        return data
Exemplo n.º 9
0
    def preview(self):
        #=================
        '''Preview map in window'''

        theurl = self.FILENAME.get()
        toconsola('TEST SHOW theurl >>' + theurl, wid=self.cons)
        #print('TEST SHOW theurl >>',theurl)
        if empty(theurl):
            messagebox.showinfo(message='No image selected')
            return
        self.ax1.clear()

        toconsola('Preview of ' + theurl, wid=self.cons)
        #print('Preview of ',theurl)
        icdf = Dataset(theurl, 'r')
        lon = icdf.variables['lon'][:]
        lat = icdf.variables['lat'][:]
        sst = icdf.variables['mcsst'][0, :, :].squeeze()
        icdf.close()

        xxT, yyT = np.meshgrid(lon, lat)

        SOUTH = np.min(lat)
        NORTH = np.max(lat)
        WEST = np.min(lon)
        EAST = np.max(lon)

        #print([EAST, WEST,SOUTH, NORTH])
        #EG mod faltan los detalles line,fill
        self.ax1.set_extent([EAST, WEST, SOUTH, NORTH])
        self.ax1.coastlines('110m', linewidth=2)
        #EG pcolormesh is faster
        #self.ax1.contourf(xxT,yyT,sst,transform=ccrs.PlateCarree())
        self.ax1.pcolormesh(xxT, yyT, sst, transform=ccrs.PlateCarree())

        #m = Basemap(llcrnrlat=SOUTH,urcrnrlat=NORTH, \
        #llcrnrlon=WEST,urcrnrlon=EAST,  \
        #ax=self.ax1)
        #m.fillcontinents(color='coral')
        #m.drawcoastlines(linewidth=1)
        #m.contourf(xxT,yyT,sst)
        #EG

        self.canvas.draw()
        toconsola('done', wid=self.cons)
Exemplo n.º 10
0
        def read_trajectory_txt(filename):
            # --------------------------------------
            '''Read a trajectory from a txt file'''

            with open(filename, 'r') as f:
                first_line = f.readline()

            self.MESSAGE += '\nReading txt file ' + filename
            if self.cons: toconsola(self.MESSAGE, wid=self.cons)
            else: print(self.MESSAGE)

            win = tk.Toplevel()
            win.title('Float column')
            Axes = Select_Columns(win, first_line, ' ')
            win.wait_window()

            self.nfloats = None
            self.nrecords = None
            self.lon = []
            self.lat = []
            self.DATE = []
            if Axes.lon is None:
                return
            if Axes.lat is None:
                return

            with open(filename) as datafile:
                for line in datafile.readlines():
                    line = line.strip()
                    line = ' '.join(line.split())
                    columns = line.split(Axes.SEPARATOR.get())

                    self.lon.append(float(columns[Axes.lon]))
                    self.lat.append(float(columns[Axes.lat]))
                    if Axes.type == 0:
                        year = int(columns[Axes.year])
                        month = int(columns[Axes.month])
                        day = int(columns[Axes.day])
                        if Axes.hour is None:
                            hour = 0
                        else:
                            hour = int(columns[Axes.hour])
                        if Axes.minute is None:
                            minute = 0
                        else:
                            minute = int(columns[Axes.minute])
                        if Axes.second is None:
                            second = 0
                        else:
                            second = int(columns[Axes.second])
                        self.DATE.append(datetime.datetime(year,month,day, \
                                                           hour,minute,second))
                    elif Axes.type == 1:
                        self.DATE.append(
                            datetime.datetime.strptime(columns[Axes.date],
                                                       Axes.fmt))

                    elif Axes.type == 2:
                        self.DATE.append(datetime.datetime.strptime(columns[Axes.date]+ \
                                         'T'+columns[Axes.time],Axes.fmt))

                    elif Axes.type == 3:
                        jd = float(columns[Axes.jday])
                        a = caldat(jd)
                        self.DATE.append(
                            datetime.datetime(a[0], a[1], a[2], a[3], a[4],
                                              a[5]))

                    else:
                        self.MESSAGE += 'unknown ASCII file format'
                        if self.cons: toconsola(self.MESSAGE, wid=self.cons)
                        else: print(self.MESSAGE)
                        return

            self.nfloats = 1
            self.nrecords = len(self.lon)
            self.lon = np.array(self.lon)
            self.lat = np.array(self.lat)
Exemplo n.º 11
0
        def read_trajectory_json(filename):
            # --------------------------------------
            '''Read a trajectory from a json file'''
            import json

            if filename[0:5].lower() == 'http:':
                self.MESSAGE += '\nReading remote json file.. ' + filename.split(
                    "/")[-1]
                self.MESSAGE += '\nPath: ' + '/'.join(
                    filename.split("/")[:-1]) + "/n"
                if self.cons: toconsola(self.MESSAGE, wid=self.cons)

                response = urllib.request.urlopen(filename)
                data = response.read()
                text = data.decode('utf-8')
                DATA = json.loads(text)
            else:
                self.MESSAGE += '\nReading local json file.. ' + filename.split(
                    "/")[-1]
                self.MESSAGE += '\nPath: ' + '/'.join(
                    filename.split("/")[:-1]) + "/n"
                if self.cons: toconsola(self.MESSAGE, wid=self.cons)
                else: print(self.MESSAGE)

                with open(filename) as datafile:
                    DATA = json.load(datafile)

            nfeatures = len(DATA["features"])
            self.MESSAGE += "\nNumber of features: " + str(nfeatures)
            if self.cons: toconsola(self.MESSAGE, wid=self.cons)
            else: print(self.MESSAGE)
            # Detect the GEOJSON MODE
            # In the "Dated LineString", the date is stored in the property "time"
            # of the trajectory
            # In the "Undated LineString", the date is stored in the points
            #

            pline = [DATA["features"][i]["geometry"]["type"] \
                                 for i in range(nfeatures)].index("LineString")

            try:
                nl = DATA["features"][pline]["properties"]["time"]["data"]
                fileFormat = "Dated LineString"
            except:
                fileFormat = "Undated LineString"

            self.lon = []
            self.lat = []
            self.DATE = []

            if fileFormat == "Undated LineString":
                for i in range(nfeatures):
                    if DATA["features"][i]["geometry"]["type"] == "Point":
                        a = DATA["features"][i]["geometry"]["coordinates"]
                        b = DATA["features"][i]["properties"]["time"]
                        self.lon.append(a[0])
                        self.lat.append(a[1])
                        self.DATE.append(datetime.datetime.strptime(b, \
                                         '%Y-%m-%dT%H:%M:%SZ'))

            elif fileFormat == "Dated LineString":
                POINTS = DATA["features"][pline]["geometry"]["coordinates"]
                DATES = DATA["features"][pline]["properties"]["time"]["data"]
                for i in range(len(DATES)):
                    self.lon.append(POINTS[i][0])
                    self.lat.append(POINTS[i][1])
                    self.DATE.append(datetime.datetime.strptime(DATES[i], \
                                     '%Y-%m-%dT%H:%M:%SZ'))

            else:
                self.MESSAGE += 'Unknown GEOJSON file format'
                if self.cons: toconsola(self.MESSAGE, wid=self.cons)
                else: print(self.MESSAGE)

            self.nfloats = 1
            self.nrecords = len(self.lon)
            self.lon = np.array(self.lon)
            self.lat = np.array(self.lat)
Exemplo n.º 12
0
        def read_trajectory_ncdf(filename):
            # --------------------------------------
            '''Read a set of trajectories from a netcdf file'''

            #EG
            self.MESSAGE += '\n Reading netcdf file - ' + filename
            if self.cons: toconsola(self.MESSAGE, wid=self.cons)
            else: print(self.MESSAGE)

            ncid = Dataset(filename)
            self.nfloats = ncid.dimensions['floats'].size
            self.nrecords = ncid.dimensions['time'].size

            # Check time dimensions:
            # In BLM files, the time variables has a unique dimension.
            # In MLM files, the time variables has two dimensions.
            #
            if len(ncid.variables['time'].shape) == 1:
                self.SOURCE = 'blm'
            elif len(ncid.variables['time'].shape) == 2:
                self.SOURCE = 'mlm'
            else:
                #EG
                self.MESSAGE += '\nError: Unknown Trajectory source'
                if self.cons: toconsola(self.MESSAGE, wid=self.cons)
                else: print(self.MESSAGE)
                return

            try:
                self.lon = ncid.variables['lon'][:, :].squeeze()
            except:
                self.lon = ncid.variables['longitude'][:, :]

            try:
                self.lat = ncid.variables['lat'][:, :].squeeze()
            except:
                self.lat = ncid.variables['latitude'][:, :]

            # If some longitudes have missing values, we set them
            # equal to nan:
            #
            try:
                self.lon = self.lon.filled(fill_value=np.nan)
            except:
                pass
            try:
                self.lat = self.lat.filled(fill_value=np.nan)
            except:
                pass

            # Get the date of the floats:
            #
            if self.SOURCE == 'blm':
                # ------------------------
                Time_blm = ncid.variables['time'][:]
                Time_units = ncid.variables['time'].units
                Time_calendar = ncid.variables['time'].calendar
                self.DATE = []
                for i in range(self.nrecords):
                    tmp = num2date(Time_blm[i],       \
                                   units=Time_units,    \
                                   calendar=Time_calendar)
                    s = tmp.strftime('%Y-%m-%d %H:%M:%S')
                    d = datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
                    self.DATE.append(d)
                #Time_jd = ncid.variables['time'][:]
                #self.DATE = []
                #for i in range(self.nrecords):
                #  a = caldat(Time_jd[i])
                #  self.DATE.append(datetime.datetime(a[0],a[1],a[2],a[3],a[4],a[5]))
            elif self.SOURCE == 'mlm':
                # ------------------------
                Time_jd = ncid.variables['time'][:, :]
                Time_jd[Time_jd > 1e10] = np.nan

                self.DATE = []
                for j in range(ncid.variables['time'].shape[0]):
                    tmpdate = []
                    for i in range(self.nfloats):
                        a = caldat(Time_jd[j, i])
                        if np.isnan(a[0]):
                            tmpdate.append(
                                datetime.datetime(6050, 1, 1, 12, 0, 0))
                        else:
                            tmpdate.append(
                                datetime.datetime(a[0], a[1], a[2], a[3], a[4],
                                                  a[5]))
                    self.DATE.append(tmpdate)
Exemplo n.º 13
0
    def Read(self, filename):
        # ======================
        '''Opens and reads a trajectory file'''

        __version__ = "0.3"
        __author__ = "Quim Ballabrera"
        __date__ = "February 2018"

        self.FILENAME.set(filename)

        # --------------------------------------
        def read_trajectory_ncdf(filename):
            # --------------------------------------
            '''Read a set of trajectories from a netcdf file'''

            #EG
            self.MESSAGE += '\n Reading netcdf file - ' + filename
            if self.cons: toconsola(self.MESSAGE, wid=self.cons)
            else: print(self.MESSAGE)

            ncid = Dataset(filename)
            self.nfloats = ncid.dimensions['floats'].size
            self.nrecords = ncid.dimensions['time'].size

            # Check time dimensions:
            # In BLM files, the time variables has a unique dimension.
            # In MLM files, the time variables has two dimensions.
            #
            if len(ncid.variables['time'].shape) == 1:
                self.SOURCE = 'blm'
            elif len(ncid.variables['time'].shape) == 2:
                self.SOURCE = 'mlm'
            else:
                #EG
                self.MESSAGE += '\nError: Unknown Trajectory source'
                if self.cons: toconsola(self.MESSAGE, wid=self.cons)
                else: print(self.MESSAGE)
                return

            try:
                self.lon = ncid.variables['lon'][:, :].squeeze()
            except:
                self.lon = ncid.variables['longitude'][:, :]

            try:
                self.lat = ncid.variables['lat'][:, :].squeeze()
            except:
                self.lat = ncid.variables['latitude'][:, :]

            # If some longitudes have missing values, we set them
            # equal to nan:
            #
            try:
                self.lon = self.lon.filled(fill_value=np.nan)
            except:
                pass
            try:
                self.lat = self.lat.filled(fill_value=np.nan)
            except:
                pass

            # Get the date of the floats:
            #
            if self.SOURCE == 'blm':
                # ------------------------
                Time_blm = ncid.variables['time'][:]
                Time_units = ncid.variables['time'].units
                Time_calendar = ncid.variables['time'].calendar
                self.DATE = []
                for i in range(self.nrecords):
                    tmp = num2date(Time_blm[i],       \
                                   units=Time_units,    \
                                   calendar=Time_calendar)
                    s = tmp.strftime('%Y-%m-%d %H:%M:%S')
                    d = datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
                    self.DATE.append(d)
                #Time_jd = ncid.variables['time'][:]
                #self.DATE = []
                #for i in range(self.nrecords):
                #  a = caldat(Time_jd[i])
                #  self.DATE.append(datetime.datetime(a[0],a[1],a[2],a[3],a[4],a[5]))
            elif self.SOURCE == 'mlm':
                # ------------------------
                Time_jd = ncid.variables['time'][:, :]
                Time_jd[Time_jd > 1e10] = np.nan

                self.DATE = []
                for j in range(ncid.variables['time'].shape[0]):
                    tmpdate = []
                    for i in range(self.nfloats):
                        a = caldat(Time_jd[j, i])
                        if np.isnan(a[0]):
                            tmpdate.append(
                                datetime.datetime(6050, 1, 1, 12, 0, 0))
                        else:
                            tmpdate.append(
                                datetime.datetime(a[0], a[1], a[2], a[3], a[4],
                                                  a[5]))
                    self.DATE.append(tmpdate)

        # --------------------------------------
        def read_trajectory_json(filename):
            # --------------------------------------
            '''Read a trajectory from a json file'''
            import json

            if filename[0:5].lower() == 'http:':
                self.MESSAGE += '\nReading remote json file.. ' + filename.split(
                    "/")[-1]
                self.MESSAGE += '\nPath: ' + '/'.join(
                    filename.split("/")[:-1]) + "/n"
                if self.cons: toconsola(self.MESSAGE, wid=self.cons)

                response = urllib.request.urlopen(filename)
                data = response.read()
                text = data.decode('utf-8')
                DATA = json.loads(text)
            else:
                self.MESSAGE += '\nReading local json file.. ' + filename.split(
                    "/")[-1]
                self.MESSAGE += '\nPath: ' + '/'.join(
                    filename.split("/")[:-1]) + "/n"
                if self.cons: toconsola(self.MESSAGE, wid=self.cons)
                else: print(self.MESSAGE)

                with open(filename) as datafile:
                    DATA = json.load(datafile)

            nfeatures = len(DATA["features"])
            self.MESSAGE += "\nNumber of features: " + str(nfeatures)
            if self.cons: toconsola(self.MESSAGE, wid=self.cons)
            else: print(self.MESSAGE)
            # Detect the GEOJSON MODE
            # In the "Dated LineString", the date is stored in the property "time"
            # of the trajectory
            # In the "Undated LineString", the date is stored in the points
            #

            pline = [DATA["features"][i]["geometry"]["type"] \
                                 for i in range(nfeatures)].index("LineString")

            try:
                nl = DATA["features"][pline]["properties"]["time"]["data"]
                fileFormat = "Dated LineString"
            except:
                fileFormat = "Undated LineString"

            self.lon = []
            self.lat = []
            self.DATE = []

            if fileFormat == "Undated LineString":
                for i in range(nfeatures):
                    if DATA["features"][i]["geometry"]["type"] == "Point":
                        a = DATA["features"][i]["geometry"]["coordinates"]
                        b = DATA["features"][i]["properties"]["time"]
                        self.lon.append(a[0])
                        self.lat.append(a[1])
                        self.DATE.append(datetime.datetime.strptime(b, \
                                         '%Y-%m-%dT%H:%M:%SZ'))

            elif fileFormat == "Dated LineString":
                POINTS = DATA["features"][pline]["geometry"]["coordinates"]
                DATES = DATA["features"][pline]["properties"]["time"]["data"]
                for i in range(len(DATES)):
                    self.lon.append(POINTS[i][0])
                    self.lat.append(POINTS[i][1])
                    self.DATE.append(datetime.datetime.strptime(DATES[i], \
                                     '%Y-%m-%dT%H:%M:%SZ'))

            else:
                self.MESSAGE += 'Unknown GEOJSON file format'
                if self.cons: toconsola(self.MESSAGE, wid=self.cons)
                else: print(self.MESSAGE)

            self.nfloats = 1
            self.nrecords = len(self.lon)
            self.lon = np.array(self.lon)
            self.lat = np.array(self.lat)

        # --------------------------------------
        def read_trajectory_txt(filename):
            # --------------------------------------
            '''Read a trajectory from a txt file'''

            with open(filename, 'r') as f:
                first_line = f.readline()

            self.MESSAGE += '\nReading txt file ' + filename
            if self.cons: toconsola(self.MESSAGE, wid=self.cons)
            else: print(self.MESSAGE)

            win = tk.Toplevel()
            win.title('Float column')
            Axes = Select_Columns(win, first_line, ' ')
            win.wait_window()

            self.nfloats = None
            self.nrecords = None
            self.lon = []
            self.lat = []
            self.DATE = []
            if Axes.lon is None:
                return
            if Axes.lat is None:
                return

            with open(filename) as datafile:
                for line in datafile.readlines():
                    line = line.strip()
                    line = ' '.join(line.split())
                    columns = line.split(Axes.SEPARATOR.get())

                    self.lon.append(float(columns[Axes.lon]))
                    self.lat.append(float(columns[Axes.lat]))
                    if Axes.type == 0:
                        year = int(columns[Axes.year])
                        month = int(columns[Axes.month])
                        day = int(columns[Axes.day])
                        if Axes.hour is None:
                            hour = 0
                        else:
                            hour = int(columns[Axes.hour])
                        if Axes.minute is None:
                            minute = 0
                        else:
                            minute = int(columns[Axes.minute])
                        if Axes.second is None:
                            second = 0
                        else:
                            second = int(columns[Axes.second])
                        self.DATE.append(datetime.datetime(year,month,day, \
                                                           hour,minute,second))
                    elif Axes.type == 1:
                        self.DATE.append(
                            datetime.datetime.strptime(columns[Axes.date],
                                                       Axes.fmt))

                    elif Axes.type == 2:
                        self.DATE.append(datetime.datetime.strptime(columns[Axes.date]+ \
                                         'T'+columns[Axes.time],Axes.fmt))

                    elif Axes.type == 3:
                        jd = float(columns[Axes.jday])
                        a = caldat(jd)
                        self.DATE.append(
                            datetime.datetime(a[0], a[1], a[2], a[3], a[4],
                                              a[5]))

                    else:
                        self.MESSAGE += 'unknown ASCII file format'
                        if self.cons: toconsola(self.MESSAGE, wid=self.cons)
                        else: print(self.MESSAGE)
                        return

            self.nfloats = 1
            self.nrecords = len(self.lon)
            self.lon = np.array(self.lon)
            self.lat = np.array(self.lat)

        filename = self.FILENAME.get()
        if filename.lower().endswith(('.nc', '.cdf', '.ncdf')):
            read_trajectory_ncdf(filename)

        elif filename.lower().endswith(('.geojson', '.json')):
            read_trajectory_json(filename)

        else:
            read_trajectory_txt(filename)

#    elif filename.lower().endswith(('.txt')):
#      read_trajectory_txt(filename)
#
#    elif filename.lower().endswith(('.csv')):
#      print('csv: not yet coded')
#      self.nfloats  = None
#      self.nrecords = None
#
#    elif filename.lower().endswith(('.dat','.data')):
#      print('ascii data: not yet coded')
#      self.nfloats  = None
#      self.nrecords = None

# Cheack that something has been read:
        if self.nfloats is None:
            self.MESSAGE += '\nReading txt file.. ' + filename.split("/")[-1]
            self.MESSAGE += '\nPath: ' + '/'.join(filename.split("/")[:-1])
            if self.cons: toconsola(self.MESSAGE, wid=self.cons)
            else: print(self.MESSAGE)
            self = None
            return

        self.TIME = []
        for i in range(self.nrecords):
            self.TIME.append(self.DATE[i].timestamp())
        self.TIME = np.array(self.TIME)

        self.DATE = np.array(self.DATE)

        # If we have data, we fill some fields to their default value.
        self.I.set(0)
        self.L.set(0)
        self.L1.set(0)
        self.L2.set(self.nrecords - 1)
        self.FLOAT_COLOR = []
        self.FLOAT_SHOW = []
        self.FLOAT_ZORDER = []
        for i in range(self.nfloats):
            self.FLOAT_COLOR.append(
                tk.StringVar(value=self.PLOT.LINE_COLOR.get()))
            self.FLOAT_SHOW.append(tk.BooleanVar(value=True))
            self.FLOAT_ZORDER.append(tk.IntVar(value=self.PLOT.ZORDER.get()))